It works when loaded from file, but not when typed into ghci. Why?

て烟熏妆下的殇ゞ 提交于 2019-12-17 20:46:14

问题


If I put the following 2 lines into foobar.hs

f 1 = 1
f x = f (x-1)

then

$ ghci
> :load foobar.hs
> f 5
1

but if I do

$ ghci
> let f 1 = 1
> let f x = f (x-1)
> f 5
^CInterrupted.

then it does not return. Why?


回答1:


The latter binding overrides the former. Use this in ghci:

Prelude> :{
Prelude| let f 1 = 1
Prelude|     f x = f (x-1)
Prelude| :}
Prelude> f 5
1

Or, without the layout:

Prelude> let f 1 = 1; f x = f (x-1)
Prelude> f 5
1



回答2:


You have to enter it all in on one line, or using :{ and :} to enter multiple lines:

> let { f 1 = 1; f x = f (x - 1) }

Or

> :{
>   let f 1 = 1
>       f x = f (x - 1)
>   :}

When you use two let statements to define f, you are actually redefining f the second time, not adding to its definition. If you were to do

> let x = 1
> let x = 5

Then, x would be 5, not 1. The same goes for functions. First, you define f as f 1 = 1. Next, you define f as f x = f (x - 1), which overwrites the previous definition for f.



来源:https://stackoverflow.com/questions/19210660/it-works-when-loaded-from-file-but-not-when-typed-into-ghci-why

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