如何跨多行在ghci中定义函数? [英] How to define a function in ghci across multiple lines?
问题描述
我正在尝试在 ghci 中定义任何跨越多行的简单函数,以以下为例:
I'm trying to define any simple function that spans multiple lines in ghci, take the following as an example:
let abs n | n >= 0 = n
| otherwise = -n
到目前为止,我已经尝试在第一行之后按 Enter 键:
So far I've tried pressing Enter after the first line:
Prelude> let abs n | n >= 0 = n
Prelude> | otherwise = -n
<interactive>:1:0: parse error on input `|'
我也尝试使用 :{
和 :}
命令,但我没有走远:
I've also attempted to use the :{
and :}
commands but I don't get far:
Prelude> :{
unknown command ':{'
use :? for help.
我在 Linux 上为 Haskell 98 使用 GHC Interactive 6.6 版,我缺少什么?
I'm using GHC Interactive version 6.6 for Haskell 98 on Linux, what am I missing?
推荐答案
对于守卫(就像你的例子),你可以把它们都放在一行上就行了(守卫不关心间距)
For guards (like your example), you can just put them all on one line and it works (guards do not care about spacing)
let abs n | n >= 0 = n | otherwise = -n
如果你想用多个模式匹配参数的定义来编写你的函数,像这样:
If you wanted to write your function with multiple definitions that pattern match on the arguments, like this:
fact 0 = 1
fact n = n * fact (n-1)
然后你会使用大括号和分号分隔定义
Then you would use braces with semicolons separating the definitions
let { fact 0 = 1 ; fact n = n * fact (n-1) }
这篇关于如何跨多行在ghci中定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!