Haskell中的无限循环? (新手) [英] Infinite loop in haskell? (newbie)

查看:80
本文介绍了Haskell中的无限循环? (新手)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习Haskell。我认为这会产生一个阶乘函数...



(在ghci内)

 前奏>让ft 0 = 1 
前奏>让ft n = n * ft(n-1)
前奏> ft 5

(无限期挂起,直到^ C)。

有人可以指引我正确的方向吗?

谢谢!

解决方案

两个单独的 let 语句彼此独立解释。首先定义一个函数 ft 0 = 1 ,然后一个新函数 ft n = n * ft(n-1),覆盖第一个定义。

要用两种情况定义一个函数,您必须将两个个案放入单个 let 语句中。要在GHCI提示符下单行执行此操作,您可以通过; 来分隔两个案例:

 前奏>让ft 0 = 1; ft n = n * ft(n  -  1)
Prelude> ft 5
120


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!

解决方案

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

这篇关于Haskell中的无限循环? (新手)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆