我正在尝试对指数函数进行简单的实现,如下所示:
{-# LANGUAGE BangPatterns #-}
fact :: (Integral a) => a -> a
fact n = foldr (*) 1 [n,(n-1)..1]
-- Sum of x^i / i! over i, from i=0 to i=n
e' :: (Eq a, Integral a, Fractional a) => a -> a -> a
e' _ 0 = 1.0
e' x n = p / f + e' x (n-1)
where
!f = fact n
!p = x^n
但无法使其工作,因为我无法在控制台上显示结果,因为此消息与 Show
相关:
<interactive>:108:1:
No instance for (Show a0) arising from a use of 'print'
The type variable 'a0' is ambiguous
Note: there are several potential instances:
instance Show Double -- Defined in 'GHC.Float'
instance Show Float -- Defined in 'GHC.Float'
instance (Integral a, Show a) => Show (Ratio a)
-- Defined in 'GHC.Real'
...plus 90 others
In a stmt of an interactive GHCi command: print it
>
我知道与 Show
尝试显示的类型有关,因此尝试对其进行转换,但没有成功:e' 1 15::Integer
即使我最初想使用 (Eq a,积分 a,分数 b) => a -> a -> b
没有成功。
问题是:
<强>1。我怎样才能使这段代码工作?我不明白如何正确解决不明确
问题。
<强>2。我如何使用除 (Eq a, Integral a, Fractional a) => a -> a -> a
之外的其他类型(如果可能的话可能更合适)?
最佳答案
正如评论中提到的,没有任何类型同时是Integral
和Fractional
的成员。您未能使用的类型确实是正确的类型,只是您需要使用 fromIntegral< 从
.Integral
转换 f
和 p
/
这是经过适当修改的代码:
e :: (Eq a, Integral a, Fractional b) => a -> a -> b
e _ 0 = 1.0
e 1 _ = 1.0
e x n = p / f + e x (n-1)
where
!f = fromIntegral (fact n)
!p = fromIntegral (x^n)
关于haskell - 指数函数的简单实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26554020/