Understanding the Haskell List

sum1::[Int]->[Int]
sum1 [] =0
sum1 (x:xs) = [x|x<-xs,x `mod` 2 ==0]

I need to return numbers that are divisible by 2 when the list is provided, but the code above gives me this compilation error:

 Instance of Num [Int] required for definition of sum1

Also explain what it does (x:xs). Is this an X of the xs list ?

If we want to get the nth element of the list, how do we get it?

+3
source share
4 answers

You asked a few questions so that I answer them one by one.

Question 1: why does the compiler tell me Instance of Num [Int] required for definition of sum1?

You have created a function with a name sum1with a type [Int]->[Int]. However, consider a line sum1 [] = 0: this returns Int, not [Int]. The solution to this problem is to change the line to sum1 [] = [].

2: (x:xs)?

Haskell -, pattern matching. , , , x xs - , .

, sum1 [1,2,3], x 1, xs [2,3].

3: n- , ?

!! - , , , + *. , [1,2,3]!!1 2.


, , , . , .

+15
sum1::[Int]->[Int]
sum1 [] = [0] // problem here 
sum1 (x:xs) = [x| x <- xs ,x `mod` 2 == 0]

sum1 [Int], Int.

, (x:xs), x, xs.

, sum1 ,

sum1::[Int]->[Int]
sum1 [] = [0] // problem here 
sum1 xs = [x| x <- xs ,x `mod` 2 == 0]

. [2..10] . 2 .

n - xs haskell

xs !! n

*Main> [1..10] !! 5
6

, , . ( !) Hugs Errors.

+1

, , , : P

2: (x: xs)?

Lists in Haskell are created: HEAD + TAIL, where HEAD is the first element and the rest are the rest.

"head [1,2,3]" will return 1

"tail [1,2,3]" will return [2,3]

But there are other functions:

"init [1,2,3] will return [1,2]" last [1,2,3] will return 3

If you are starting with Haskell, check this

PS: Sorry for my bad english!

+1
source

You don't need anker using list comprehension!

sum1 = \xs -> [ x | x <- xs, mod x 2 == 0]

Another solution for the nth element:

nth_elem = \n xs -> head $ [ x | (id,x) <- zip [1..] xs, id == n ]
+1
source

All Articles