Infinite loop in haskell? (newbie)

感情迁移 提交于 2019-12-19 05:06:13

问题


I'm just learning Haskell. I thought this would produce a factorial function...

(within ghci)

Prelude> let ft 0 = 1
Prelude> let ft n = n * ft (n - 1)
Prelude> ft 5

(hangs indefinitely, until ^C).

Can someone point me in the right direction?

Thanks!


回答1:


The two separate let statements are interpreted independently from each other. First a function ft 0 = 1 is defined, and then a new function ft n = n * ft (n - 1) is defined, overwriting the first definition.

To define one function with two cases you have to put both cases into a single let statement. To do this in a single line at the GHCI prompt you can separate the two cases by ;:

Prelude> let ft 0 = 1; ft n = n * ft (n - 1)
Prelude> ft 5
120


来源:https://stackoverflow.com/questions/2901360/infinite-loop-in-haskell-newbie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!