简体   繁体   中英

How to implement ++ in Haskell?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM