Tech Off Thread

3 posts

Haskell question

Back to Forum: Tech Off
  • User profile image

    Can somebody explain to me why the following works:

    add2 = foldr (\ x xs -> x + 2 : xs) []


    but this does not:

    appendTest = foldr(\ x xs -> x ++ "Test" : xs) []


    I get a type mismatch between [[[Char]]] and [[Char]] when I call

    appendTest ["one", "two"]


    I need to do it this way:


    appendTest = foldr(\ x xs -> (\ x -> x++ "Test") : xs) []


    I am not sure why though, especially since the Int example works. Sure, String is [Char], but I can't see why the first version of appendTest expects a [[[Char]]] instead of a [[Char]].


    Thanks a lot!

  • User profile image

    Have you tried reformulating as separate functions rather than "trying to be smart on the first go" with the embedded lambda expression? When I'm doing Haskell it helps to identify problem areas.

  • User profile image
    A N Satrawala

    it may be due to + binding with higher precedence compared to : in comparison with ++

    placing brackets like should work (x ++ "Test")

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.