user3097712
user3097712

Reputation: 1675

Haskell code - a list of lists as an argument

I´ve written the following code:

set :: [[Int]] -> [Int]

set [[]]    = []

set ((x:xs)) = x : set xs 

I have as an argument a list of lists. And I try to make it to one list. In the first declaration I wanted to say that an empty list in a list should give me an empty list. In the second, I wanted to express that I take the first element of a list and insert it to the new list and so on.

But when I compile this then I get the following message:

Couldnt match the expected type ´Int´ with actual type ´[Int]´
In the first argument of (:) namely 'x'
In the expression: x: set xs

How can i fix it ?

Upvotes: 0

Views: 240

Answers (2)

Lee Duhem
Lee Duhem

Reputation: 15121

For your reference, here is a correct definition:

flatten [] = []
flatten (x:xs) = x ++ flatten xs

Testing:

> flatten [[1,2],[3,4,5],[6]]
[1,2,3,4,5,6]

Upvotes: 0

Mikhail Glushenkov
Mikhail Glushenkov

Reputation: 15078

(x:xs) has type [[Int]]. So x has type [Int] and xs has type [[Int]]. Now, your function is expected to give an answer of type [Int], but x : set xs can't possibly have that type. Do you see why?

Hint: look at the type of the : operator.

Upvotes: 2

Related Questions