简体   繁体   English

Haskell 无法匹配由签名给出的类型

[英]Haskell Couldn't match type, that is given by signature

Okay hi guys, I am having a weird problem.好的,大家好,我遇到了一个奇怪的问题。

hist :: [Int] -> [Int]
hist x = (foldr (+) 0 x)

The code above does not work, because trying to compile I am getting the error, that expected type '[Int]' could not be matched with actual type 'Int'.上面的代码不起作用,因为尝试编译时出现错误,预期类型“[Int]”无法与实际类型“Int”匹配。 I don't get that.我不明白。

Fun Fact: when I delete the signature, the function works fine!有趣的事实:当我删除签名时,该功能工作正常! Does anybody know the fault?有人知道错吗?

Thank you!谢谢!

The output of the foldr (+) 0 x will be an Int , not an [Int] . foldr (+) 0 x的输出将是Int ,而不是[Int] If you want a list, you can use scanl , but I guess, you still want foldr :如果你想要一个列表,你可以使用scanl ,但我想,你仍然想要foldr

hist :: [Int] -> Int
hist = foldr (+) 0

I however strongly advise to make use of sum :: (Foldable f, Num a) => fa -> a which also calculates the sum, but on all types that are instances of Num , and for all Foldable s (and thus not only a list).然而,我强烈建议使用sum :: (Foldable f, Num a) => fa -> a ,它也计算总和,但在所有Num实例的类型上,并且对于所有Foldable s(因此不仅一个列表)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM