1

So this one seems like it should be super-simple... but I'm not sure where to stick the 'fold' in (obviously you could fold either way)...

It says "write a function ( intToString :: [Int] -> [Char] ) using a fold, that mimics this map:

map intToDigit [5,2,8,3,4] == "52834"

And then says, "For the conversion, use intToDigit :: Int -> Char from Data.Char."

I'm not entirely sure I get the point... but yet it doesn't seem like it should be that hard -- you're just reading in the list (folding it in, I get how folds work in general) from either the left or right and doing the conversion... but I'm not sure how to set it up.

Stormy
  • 172
  • 1
  • 1
  • 9

1 Answers1

3

It is not difficult, think about the definition foldr (or foldl) of List:

 foldr::(a -> b -> b) -> b -> [a] -> b

Here (a->b->b) is the step function which will be applied on each element of list [a], b is your target.

Now, you have a list of Int ([Int]), and need to convert to [Char] (or String).

Relpace [a] by [5,2,8,3,4], b by []::[Char] (your target) and (a->b->b) by step function :

foldr step ([]::[Char]) [5,2,8,3,4]

We have known that step function has type (a->b->b), specifically, (Int->[Char]->[Char]), the job need to do just convert Int to [Char], as mentioned in question: intToDigit can be helped to convert Int to Char and (:) operator can append element at the head of List so:

step x s = intToDigit x : s

where s is [Char] (or String), put them all:

foldr (\x s->intToDigit x : s) [] [5,2,8,3,4]
assembly.jc
  • 2,056
  • 1
  • 7
  • 16
  • Aha! I didn't think it was *that* difficult, but for some reason I just couldn't get it put together correctly and just kept getting more confused. Thanks for helping straighten out my brain! Playing around with it a little I could use it as a stand-alone lambda expression or in a function and changed it to use a `foldl` too. I am loving learning Haskell! – Stormy Nov 15 '18 at 01:54
  • @Stormy Yes, Haskell is funny! Actually, foldl can be implemented by foldr, learning that can understand them in deep, if you have interested, see [Defining foldl in terms of foldr] https://stackoverflow.com/questions/6172004/writing-foldl-using-foldr – assembly.jc Nov 15 '18 at 04:57