如何在Haskell中返回积分? [英] How to return an Integral in Haskell?
问题描述
我试图弄清楚Haskell,但是我对'Integral'有点迷恋.据我了解,Int和Integer都是整数.但是,如果我尝试编译这样的函数:
I'm trying to figure out Haskell, but I'm a bit stuck with 'Integral'. From what I gather, Int and Integer are both Integral. However if I try to compile a function like this:
lastNums :: Integral a => a -> a
lastNums a = read ( tail ( show a ) ) :: Integer
我知道
Could not deduce (a ~ Integer)
from the context (Integral a)
如何返回积分?
也可以说我必须坚持使用该功能签名.
Also lets say I have to stick to that function signature.
推荐答案
让我们用英语阅读此函数类型签名.
Let's read this function type signature in English.
lastNums :: Integral a => a -> a
这意味着让调用者选择任何整数类型.lastNums函数可以采用该类型的值并产生相同类型的另一个值."
This means that "Let the caller choose any integral type. The lastNums function can take a value of that type and produce another value of the same type."
但是,您的定义始终返回 Integer
.根据类型签名,应该将决定留给调用者.
However, your definition always returns Integer
. According to the type signature, it's supposed to leave that decision up to the caller.
最简单的解决方法:
lastNums :: Integer -> Integer
lastNums = read . tail . show
定义单态函数不会感到羞耻.不要仅仅因为它可以是多态的就认为它必须是多态的.通常,多态版本会更复杂.
There's no shame in defining a monomorphic function. Don't feel it has to be polymorphic just because it can be polymorphic. Often the polymorphic version is more complicated.
这是另一种方式:
lastNums :: (Integral a, Num a) => a -> a
lastNums = fromInteger . read . tail . show . toInteger
另一种方式:
lastNums :: (Integral a, Read a, Show a) => a -> a
lastNums = read . tail . show
这篇关于如何在Haskell中返回积分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!