GHCi 中特殊情况的函数定义 [英] Function definition by special cases in GHCi
问题描述
来自 Haskell 教程:
From a Haskell tutorial:
我们可以根据情况编写整数函数.
We can write functions on integers by cases.
-- Compute the sum of the integers from 1 to n.
sumtorial :: Integer -> Integer
sumtorial 0 = 0
sumtorial n = n + sumtorial (n-1)
但是,当我尝试它时会发生以下情况:
However, here's what happens when I try it:
$ ghci
GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help
Prelude> foo 0 = print 999
Prelude> foo n = print n
Prelude> foo 0
0
我错过了什么?
推荐答案
要在 GHCi 中完全按照原样使用这些定义(即在单独的行中使用多个方程或类型签名),您需要在 GHCi 中使用多行输入通过:{
和 :}
分隔符:
To use those definition in GHCi exactly as they were written (i.e. with multiple equations or type signatures in separate lines), you need to use multiline input in GHCi through the :{
and :}
delimiters:
GHCi> :{
GHCi| foo 0 = print 999
GHCi| foo n = print n
GHCi| :}
GHCi> foo 0
999
另一种选择是使用 +m
选项在会话的其余部分启用多行输入.但是,在这种情况下,您还需要一个显式的 let
,因为没有它 GHCi 不会确定您要继续定义:
One alternative would be turing on multiline input for the rest of your session with the +m
option. In this case, though, you also need an explicit let
, as without it GHCi won't figure out you want to continue the definition:
GHCi> :set +m
GHCi> let foo 0 = print 999
GHCi| foo n = print n
GHCi|
GHCi> foo 0
999
(您可以使用 :unset +m
关闭 +m
.)
(You can turn +m
off with :unset +m
.)
另一种可能性是完全避免换行,并使用显式大括号和分号:
Yet another possibility is eschewing line breaks altogether, and using explicit braces and semicolons:
GHCi> foo 0 = print 999; foo n = print n
GHCi> foo 0
999
在多行输入选项之间,我个人更喜欢 :{
和 :}
而不是 +m
,因为它们对我通常如何表述我的定义,如果我从其他地方粘贴代码,更有可能立即起作用.
Between the multiline input options, I personally prefer :{
and :}
over +m
, as they require less changes with respect to how I usually phrase my definitions, and are more likely to work straight away if I paste code from somewhere else.
至于为什么您的输入方式不起作用,这是因为,除非您使用多行输入,否则在单独的 GHCi 行中绑定到相同名称会相互遮蔽:
As for why your way of entering it didn't work, it was because, unless you use multiline input, bindings to the same name in separate GHCi lines shadow each other:
GHCi> x = 3
GHCi> x = 4
GHCi> x
4
如果我们注意到我们从 let
表达式链中得到相同的行为,这似乎就不那么令人惊讶了:
This seems less surprising if we note that we get the same behaviour from a chain of let
-expressions:
GHCi> let x = 3 in let x = 4 in x
4
这篇关于GHCi 中特殊情况的函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!