How do I implement ++ in Haskell?

Hi I'm new to Haskell programming. I am trying to implement the "++" operator 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 got a lot of errors like with [a], [[a]] and [[[a]]]. Still confusing the type of list in Haskell. Can anyone help me with this? Thank.:)

+3


source to share


1 answer


append (es:e) xs =
        ^^^^

      

Typically, you write (e:es)

about which one would say "one e before the list es". You actually used that sense below, but told the compiler that es

is is an item and e

is a list that produces the type errors you got.

    if (null es)

      

This is not how you should be testing the emtpy list. In fact, if you name it append [] …

, you will get a "non-exhaustive pattern" error because it is (e:es)

always a list of at least one item. So try two patterns:



append []     xs = xs
append (e:es) xs = append es (e:xs)

      

However, this still doesn't work - the first list is actually canceled by this snippet. Instead, the first element ( e

) has to go to the rest of the list ( es

and xs

):

append (e:es) xs = e : (append es xs)

      

(and what is really how ++

implemented
)

+16


source







All Articles