【问题标题】:Problem expressing a simple recursive function in Haskell [duplicate]在Haskell中表达一个简单的递归函数的问题[重复]
【发布时间】:2021-12-31 19:11:30
【问题描述】:

我决定开始学习 Haskell,但在表达用于计算输入参数的阶乘的简单递归函数的语法方面遇到了一些问题。

myFac :: Integral a => a -> a
myFac 1 = 1
myFac x = x * myFac x-1

当我在 ghci 中运行它时,看起来终止条件从未被调用,并且我得到了堆栈溢出。对于下面的测试用例,我期望 1! = 1, 10! = 3628800, 2! = 2, 0.5! -> 错误情况,但得到以下结果:

*Main> myFac 1
1
*Main> myFac 10
*** Exception: stack overflow
*Main> myFac 2
*** Exception: stack overflow
*Main> myFac 0.5

<interactive>:21:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘print’
  prevents the constraint ‘(Show a0)’ from being solved.
  Probable fix: use a type annotation to specify what ‘a0’ should be.
  These potential instances exist:
    instance Show HandlePosn -- Defined in ‘GHC.IO.Handle’
    instance Show BufferMode -- Defined in ‘GHC.IO.Handle.Types’
    instance Show Handle -- Defined in ‘GHC.IO.Handle.Types’
    ...plus 27 others
    ...plus 14 instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
• In a stmt of an interactive GHCi command: print it

因此,它似乎将x 参数视为一个整数,因为它不喜欢被赋予一个浮点值,但它应该达到终止条件,但除非它从那里开始,否则它不会。

我在这里缺少一些语法吗?有什么办法可以纠正这个问题,让它按我的预期工作吗?

【问题讨论】:

    标签: haskell recursion


    【解决方案1】:
    myFac x = x * myFac x-1
    

    这一行被括号括起来

    myFac x = (x * (myFac x))-1
    

    即它使用与给出的完全相同的参数调用myFac。只需添加一些额外的括号,就可以了。考虑

    myFac x = x * myFac (x - 1)
    

    【讨论】:

      猜你喜欢
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      相关资源
      最近更新 更多