Haskell 返回有多少输入大于其平均值
我对 haskell 很陌生,编写了一个简单的代码来返回有多少输入大于其平均值。我收到错误:
错误文件:.\AverageThree.hs:5 - 应用程序中的类型错误 * 表达式:xyz 期限:x 类型:Int * 不匹配:a -> b->
代码:
averageThree :: Int -> >averageThree :: Int ->整数->整数->漂浮 平均三 xyz = (fromIntegral x+ fromIntegral y+ fromIntegral z)/3 howManyAverageThree ::Int ->整数->整数-> INT howManyAverageThree xyz = 长度 >平均三
有人帮助我吗?
I'm very new to haskell, writing a simple code that returns how many inputs are larger than their average value. I got error:
ERROR file:.\AverageThree.hs:5 - Type error in application
* Expression : x y z
Term : x
Type : Int
* Does not match : a -> b -> cCode:
averageThree :: Int -> Int -> Int -> Float averageThree x y z = (fromIntegral x+ fromIntegral y+ fromIntegral z)/3 howManyAverageThree ::Int -> Int -> Int -> Int howManyAverageThree x y z = length > averageThree
Anyone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您遇到的麻烦来自几个地方。
首先,您没有应用
length
或averageThree
函数,因此也没有使用howManyAverageThree
的参数。其次,
length
的类型为[a] ->整数。由于这里没有列表,因此您要么必须使用不同的函数,要么创建一个列表。
如果我正确理解您想要的算法,您将需要做一些事情:
x
y
和z
应用于averageThree
。filter
函数,比较这个计算结果每个传入参数的平均值;这将产生一个列表。我匆忙执行此操作的代码如下:
这利用了几个简洁的功能:
>
接受两个相同类型的参数,并返回一个 Bool - 通过用括号括起来并在一侧提供一个表达式,我已经部分应用了它,这使得它可以用作过滤器函数where
关键字。我用它来清理它并使其更具可读性。filter
函数。$
的函数应用程序。该运算符只是将函数应用从左关联更改为右关联。The trouble you're having comes from a few places.
First, you aren't applying either function,
length
oraverageThree
- and hence also not using your arguments tohowManyAverageThree
.Second, the type of
length
is[a] -> Int
. As you don't have a list here, you either have to use a different function, or make a list.If I understand your desired algorithm correctly, you are going to need to do a few things:
x
y
andz
toaverageThree
.filter
function, comparing this computed average with each passed in parameter; this will result in a list.The code I dashed off to do this follows:
This takes advantage of a couple of neat features:
>
takes two parameters of the same type, and returns a Bool - by wrapping in parenthesis and providing an expression on one side, I have partially applied it, which allows it to be used as a filter functionwhere
keyword. I used this to clean it all up a little and make it more readable.filter
function, which I mentioned above.$
. This operator just changes the function application from left-associative to right-associative.这里有很多问题:
length
没有达到您想要的效果。length
返回列表的长度,并且您的howManyAvergageThree
中没有列表
averageThree
返回 Float。howManyAverageThree
需要考虑到这一点。具体来说,>
需要其参数具有相同类型。第二个函数中对
averageThree
的调用需要一些参数。这是一个工作版本:
There are a number of problems here:
length
doesn't do what you want it to.length
returns the length of a list, and there are no lists in yourhowManyAvergageThree
averageThree
returns a Float.howManyAverageThree
needs to account for that. Specifically,>
needs its arguments to be of the same type.The call to
averageThree
in the second function needs some arguments.Here's a working version: