Re-write 'map intToDigit' with a fold…

后端 未结 1 746
無奈伤痛
無奈伤痛 2021-01-27 12:09

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

相关标签:
1条回答
  • 2021-01-27 12:58

    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]
    
    0 讨论(0)
提交回复
热议问题