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
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]