Hi I'm new in Haskell programming. I'm trying to implement operator "++" by myself. Here's a small program I wrote but it won't work:
append (es:e) xs =
if (null es)
then e:xs
else append es (e:xs)
I received lots of type error with [a],[[a]] and [[[a]]]. Still confusing about the list type in Haskell. Can someone help me with that? Thank you. :)
append (es:e) xs =
^^^^
Typically, you would write (e:es)
, which could be spoken "one e before a list of es". You actually have used this meaning below, but have told the compiler that es
is an element and e
is a list - which produces the type errors you received.
if (null es)
That's not how you should test for an emtpy list. In fact, if you'd call append [] …
you'd get a "non-exhaustive pattern" error, because (e:es)
is always a list of at least one element. So try two patterns:
append [] xs = xs
append (e:es) xs = append es (e:xs)
However, this still doesn't work expected - the first list is actually reversed by this snippet. Instead, the first element (e
) needs to go before the whole rest of the list (es
and xs
):
append (e:es) xs = e : (append es xs)
(and that's indeed how ++
is implemented)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments