简体   繁体   English

为什么这个 function 不终止于 Haskell?

[英]Why doesn't this function terminate in Haskell?

I am confused why my function nest which composes f with itself n times我很困惑为什么我的f nest与自己组成n

nest f 0 = id
nest f n = f . nest f (n - 1)

never terminates.永不终止。 I would have thought that it would "pattern match" on the case when n becomes zero.我会认为当n变为零时它会“模式匹配”。 I am defining it by typing these two lines into GHCI and calling with nest (+ 1) 2 3 for instance.例如,我通过在 GHCI 中键入这两行并使用nest (+ 1) 2 3调用来定义它。

By typing the function on two separate REPL lines, you are essentially redefining it the second time around, omitting the base case.通过在两条单独的 REPL 行上键入 function,您实际上是在第二次重新定义它,省略了基本情况。

The correct way to enter this function into the REPL is:将这个 function 输入 REPL 的正确方法是:

nest f 0 = id; nest f n = f . nest f (n - 1)

Alternatively, you can enter multiline mode with the :{ command, and leave it using :} .或者,您可以使用:{命令进入多行模式,并使用:}离开它。

When you pasted it into GHCi what you did was define one function of nest f 0 = id .当您将其粘贴到 GHCi 中时,您所做的是定义一个nest f 0 = id的 function 。 Then you said "ignore that function, I'm replacing it with a new function of the same name where the whole definition is nest fn = f. nest f (n - 1) .然后你说“忽略那个 function,我用同名的新 function 替换它,其中整个定义是nest fn = f. nest f (n - 1)

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

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