GHCi中特殊情况下的功能定义 [英] Function definition by special cases in GHCi

查看:85
本文介绍了GHCi中特殊情况下的功能定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Haskell 教程:

我们可以按大小写整数函数.

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.)

另一种可能性是完全避免换行,并使用大括号和分号:

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屋!

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