具有“无数据”的列表操作
关于列表的进一步问题:
aaa :: [[(Char, Float)]] -> Float -> [[(Char, Float)]]
aaa [[]] a = error "no indata"
aaa [[(a,b)]] c = [[(a, b/c)]]
aaa ([(a,b)]:tail) c = [(a, b/c)] : (aaa tail c)
如何使其工作:
aaa [[('a',3),('b',4),('c',5)],[('a',3),('b',4),('c',5)] ] 4
结果:
[[('a',0.75),('b',1),('c',1.25)],[('a',0.75),('b',1),('c',1.25)]]
A further question about List:
aaa :: [[(Char, Float)]] -> Float -> [[(Char, Float)]]
aaa [[]] a = error "no indata"
aaa [[(a,b)]] c = [[(a, b/c)]]
aaa ([(a,b)]:tail) c = [(a, b/c)] : (aaa tail c)
How to make it work with:
aaa [[('a',3),('b',4),('c',5)],[('a',3),('b',4),('c',5)] ] 4
the result:
[[('a',0.75),('b',1),('c',1.25)],[('a',0.75),('b',1),('c',1.25)]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有多种方法可以实现您的目标。我认为尝试显式地实现递归是有启发性的,就像您尝试做的那样。但是,我认为如果您将其分成更小的部分,您的代码会更清晰。考虑使用两个具有以下签名的函数:
然后您可以在
aaa
的实现中使用innerTransform
。当您通过显式递归实现
aaa
时,您可以尝试使用map
等函数来实现它,如另一个答案中所述。作为这个方向的中间步骤,尝试通过将innerTransform
映射到外部列表来解决它。您需要稍微调整一下 innerTransform: 的参数顺序,然后将该函数部分应用于 float 以获得:
,您可以将其用作
map
的参数。There is a number a ways you can achieve your goal. I think it is instructive to try to implement the recursion explicitly, as you have tried to do. However, I think your code will be more clear, if you split it up into smaller parts. Consider having two functions, with the following signatures:
Then you can use
innerTransform
in your implementation ofaaa
.When you have implemented
aaa
through explicit recursion, you can try to work towards implementing it with functions such asmap
, as described in another answer. As a middle step in that direction, try solving it by mappinginnerTransform
over the outer list. You need to fiddle around a bit with the argument order to innerTransform:and then partially apply that function to the float to obtain:
which you can use as an argument to
map
.使用列表理解,这可能是这样的:
Using list comprehension this could be something like :
怎么样:
您的代码片段中的类型匹配。您尝试将在浮点上定义的函数应用于整数。
您必须将浮点数传递给函数。这就是为什么我在对它们应用浮点除法“/”之前将整数(fromIntegral y)转换为浮点数。第二个参数也必须是浮点数,因此使用 4.0 而不是 4。
how about:
The types in your snippet down match. You try to apply functions defined on float on integers.
You have to pass floats to the functions. That's why i convert the integers with (fromIntegral y) to floats before applying the floating point division "/" on them. The second argument has to be a floating point number too, so use 4.0 instead of 4.