在GHCi中特殊情况下的函数定义 [英] Function definiton by special cases in GHCi

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

问题描述

从Haskell 教程


我们可以通过个案编写整数函数。



   - 计算从1到n的整数之和。 
sumtorial :: Integer - >整数
sumtorial 0 = 0
sumtorial n = n + sumtorial(n-1)

然而,当我尝试时会发生以下情况:

  $ ghci 
GHCi,版本8.0.1: http://www.haskell.org/ghc/:?寻求帮助
Prelude> foo 0 =打印999
前奏> foo n =打印n
前奏> foo 0
0

我缺少什么?


<为了在GHCi中使用你的定义和你写的一样(即用多个方程在不同的行中),你需要在GHCi中使用多行输入:{:} 分隔符:

  GHCI> :{
GHCi | foo 0 =打印999
GHCi | foo n =打印n
GHCi | :}
GHCi> foo 0
999

另一种方法是在会话的其余部分使用多行输入与 + m 选项。不过,在这种情况下,您还需要一个明确的 let ,因为如果没有它,GHCi将不会知道您想继续定义:

  GHCi> :set + m 
GHCi>让foo 0 =打印999
GHCi | foo n =打印n
GHCi |
GHCi> foo 0
999



<您可以打开 + m off与:unset + m 。)



另一种可能是完全避开换行符,并使用明确的大括号和分号:

  GHCi> foo 0 =打印999; foo n =打印n 
GHCi> foo 0
999

在多行选项之间,我个人比<$ $更喜欢明确的分隔符c $ c> + m ,因为它需要的更少的变化就我通常如何定义我的定义而言,并且如果我从其他地方粘贴代码,则更有可能直接工作。

b
$ b

至于为什么你的输入方式不起作用,这是因为,除非你使用多行输入,否则在单独的GHCi行中绑定到同一个名字会影响对方:

  GHCi> x = 3 
GHCi> x = 4
GHCi> x
4

如果我们注意到我们从 let -expressions:

  GHCi>让x = 3 in x = 4 in x 
4


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

What am I missing?

解决方案

To use your definition in GHCi exactly as you wrote it (i.e. with multiple equations 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

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

(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

Between the multiline options, I personally prefer the explicit delimiters over +m, as it requires less changes with respect to how I usually phrase my definitions, and is more likely to work straight away if I paste code from somewhere else.

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

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天全站免登陆