Search code examples
stringhaskellhigher-order-functionsfold

Should I use foldr or foldl' to build a String in Haskell?


Assuming that foldr should be used to build data structures and foldl' if the result is supposed to be a single value, I'm not sure what to use for Strings. On the one hand it is a data structure, but on the other hand a String is usually only used as a whole, meaning that short-circuiting isn't very relevant. To answer this question, it's probably crucial how functions like putStrLn use Strings, isn't it? Or am I on a completely wrong track?

EDIT: So I want my function to turn something like [(5, 's'), (1, ’a'), (3, 'd')] into sssssaddd (following an exercise from https://en.m.wikibooks.org/wiki/Haskell) and I have to choose one from those two functions:

decode :: [(Int, Char)] -> String
decode = foldr ff []
  where
    ff (l, c) xs = replicate l c ++ xs

decode' :: [(Int, Char)] -> String
decode' = foldl' ff []
  where
    ff xs (l, c) = xs ++ replicate l c

Solution

  • You're on the completely wrong track. The only correct way to decide what fold to use involves knowing what the fold will do. Knowing only the output type is not enough.