Haskell递归列表求和 [英] Haskell Recursive List Summation

查看:131
本文介绍了Haskell递归列表求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是函数式编程和haskell的新手,所以我只是通过尝试一些欧拉问题开始学习。这涉及到大量的列表总结。

所以我想写一个递归列表求和函数,它将一个列表作为输入并返回一个整数作为输出,实例:

   - 总结一个列表
listsum :: [int] - > int
listum [a:b:[]] = a + b
listsum x = head x + listsum tail x

编译此代码时,收到此错误:

 无法匹配预期类型`[[int]  - > int]'
与实际类型`[a0] - > [a0]'
相关绑定包括
x :: [int]
(绑定在C:\ Users \Rade\Documents\GitHub\haskell\euler_2.hs: 15:9)
listsum :: [int] - > int
(绑定在C:\ Users \Rade\Documents\GitHub\haskell\euler_2.hs:14:1)
可能的原因:tail应用于太少参数
在`listsum'的第一个参数中,即`tail'
在`(+)'的第二个参数中,即`listsum tail x'

我试图研究模式匹配,但我无法理解预期类型与实际类型的含义。

解决方案

  listsum [a:b:[]] = a + b 

这里, a:b:[] 表示列表 [a,b] ,所以 [a:b:[]] 表示 [[a,b]] ,这不是您想要的。



只需将其更改为

  listsum(a:b:[])= a + b 

现在,在

  listsum x = head x + listsum tail x 

零件 listsum tail x 表示 apply listsum tail ,然后将结果应用于 x 的。我想你的意思是应用 tail x ,然后应用 listsum 到结果,可以表示为 listsum(tail x)






我建议稍微清理一下实现,它假设总结空列表为零。

  listsum [] = 0 
listsum(x:t)= x + listsum t

这与您的实现功能有所不同,因为它可以正确处理带有零个或一个元素的列表。


I'm new to functional programming and haskell, so I'm just starting out learning both by attempting some Euler problems. This involves a great deal of list summations.

So I'm trying to write a recursive list summation function that takes one list as input and returns an integer as output, for instance:

-- Sum up a list
listsum :: [int] -> int
listsum [a:b:[]] = a + b
listsum x = head x + listsum tail x

When compiling this code, I receive this error:

Couldn't match expected type `[[int] -> int]'
            with actual type `[a0] -> [a0]'
Relevant bindings include
  x :: [int]
    (bound at C:\Users\Rade\Documents\GitHub\haskell\euler_2.hs:15:9)
  listsum :: [int] -> int
    (bound at C:\Users\Rade\Documents\GitHub\haskell\euler_2.hs:14:1)
Probable cause: `tail' is applied to too few arguments
In the first argument of `listsum', namely `tail'
In the second argument of `(+)', namely `listsum tail x'

I've tried to research the pattern matching, but I cannot understand what it means with expected type versus actual type. Where am I going wrong?

解决方案

listsum [a:b:[]] = a + b

Here, a:b:[] means the list [a, b], so [a:b:[]] means [[a, b]], which is not what you want.

Simply change this to

listsum (a:b:[]) = a + b

Now, in

listsum x = head x + listsum tail x

the part listsum tail x means apply listsum to tail, and then apply the result to x. I suppose you meant apply tail to x and then apply listsum to the result, which can be expressed as listsum (tail x).


I suggest a bit cleaner implementation, which assumes that summing empty list yields zero.

listsum [] = 0
listsum (x:t) = x + listsum t

This differs in functionality from your implementation, since it handles lists with zero or one element correctly.

这篇关于Haskell递归列表求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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