用折叠重写'map intToDigit'... [英] Re-write 'map intToDigit' with a fold...

查看:78
本文介绍了用折叠重写'map intToDigit'...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,这似乎应该非常简单...但是我不确定将折叠"粘贴在哪里(显然,您可以用任何一种方法折叠)...

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)...

它说:使用折叠来编写一个函数(intToString :: [Int] -> [Char]),该函数模仿此地图:

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

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

然后说:要进行转换,请使用Data.Char中的intToDigit :: Int -> Char."

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.

推荐答案

这并不困难,考虑一下List的定义foldr(或foldl):

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

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

此处(a->b->b)step函数,将应用于列表[a]的每个元素,b是您的目标.

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

现在,您有了一个Int([Int])列表,并且需要转换为[Char](或String).

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

使用[5,2,8,3,4]代替[a],使用[]::[Char](您的目标)使用b,使用step功能使用(a->b->b):

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]

我们知道step function具有类型(a->b->b),特别是(Int->[Char]->[Char]),工作要做的只是将Int转换为[Char],如所提到的那样:intToDigit可以帮助转换IntChar(:)运算符可以在List的开头附加元素,这样:

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

其中s是[Char](或String),则将它们全部放进去:

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

foldr (\x s->intToDigit x : s) [] [5,2,8,3,4]

这篇关于用折叠重写'map intToDigit'...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆