haskell - 指数函数的简单实现

标签 haskell types

我正在尝试对指数函数进行简单的实现,如下所示:

{-# 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 之外的其他类型(如果可能的话可能更合适)?

最佳答案

正如评论中提到的,没有任何类型同时是IntegralFractional的成员。您未能使用的类型确实是正确的类型,只是您需要使用 fromIntegral< 从 Integral 转换 fp/.

这是经过适当修改的代码:

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/

相关文章:

types - Spark Ar Code 自动完成功能在 Visual Studio Code 中不起作用

haskell - 为什么差异列表不是可折叠的实例?

multithreading - Haskell - 创建线程,写入屏幕, sleep 线程,向屏幕写入其他内容

haskell - ghc-pkg : cannot create: dist/dist-sandbox-XXXXXXXX/package. conf.inplace 已存在

c++ - (-2147483648> 0) 在 C++ 中返回 true?

types - QueΛ的投影算子是什么类型?

haskell - 带参数调用主函数

haskell - 如何从具有函数依赖的类型类中获取和使用依赖类型?

java - 类型敏感的语言可以是无类型的吗?

c++ - 模板的编译时类型别名