Re-write 'map intToDigit' with a fold…

三世轮回 提交于 2019-12-31 05:09:36

问题


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.


回答1:


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]


来源:https://stackoverflow.com/questions/53294277/re-write-map-inttodigit-with-a-fold

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!