[Haskell-beginners] Question on : usage

Michael Orlitzky michael at orlitzky.com
Mon Dec 23 14:12:25 UTC 2013


On 12/23/2013 08:55 AM, Angus Comber wrote:
> I am playing with concatenating lists so I start with this:
> 
> testconcat :: [[a]] -> [a]
> testconcat [[]] = []
> testconcat [(x:xs)] = x : xs
> 
> Now, testconcat [[]] and testconcat [[1,2]] works
> 
> So now I want to try with a 2nd inner list so I do this:
> 
> testconcat :: [[a]] -> [a]
> testconcat [[]] = []
> testconcat [(x:xs)] = x : xs
> testconcat [(x:xs), (y:ys)] = x : xs : y : ys
> 
> and I get load error:
>     Couldn't match expected type `a' with actual type `[a]'
>       `a' is a rigid type variable bound by
>           the type signature for testconcat :: [[a]] -> [a]
>           at prog_haskell.hs:218:15
>     In the first argument of `(:)', namely `xs'
>     In the second argument of `(:)', namely `xs : y : ys'
>     In the expression: x : xs : y : ys
> 

The colon operator (:) takes a single element on the left, and a list on
the right. In,

  testconcat [(x:xs), (y:ys)] = x : xs : y : ys

you've got lists on both the left and the right. This would work:

  testconcat [(x:xs), (y:ys)] = x : ( y : (xs ++ ys) )

(note: not the same function as you wanted!) since it keeps all of the
single-elements on the left-hand side of (:). You're going to need to
use (++) in at least one place, though, since you need to combine the
lists 'xs' and 'ys' somehow. The function you really want is,

  testconcat [(x:xs), (y:ys)] = (x:xs) ++ (y:ys)

but of course this is just,

  testconcat [l1, l2] = l1 ++ l2



More information about the Beginners mailing list