在学校练习
我有这个功能
bar :: Float -> Float -> Float
bar x 0 = 0
bar 0 y = 0
bar x y = x * y
Run Code Online (Sandbox Code Playgroud)
我在GHC中键入它
let bar x 0 = 0; bar 0 y = 0; bar x y = x * y
Run Code Online (Sandbox Code Playgroud)
并评估
bar foo 0
bar 0 foo
Run Code Online (Sandbox Code Playgroud)
我被要求修改吧使用'|' 所以我想做一些像:
let bar x y = | x 0 = 0 | 0 y = 0 | x y = x * y
Run Code Online (Sandbox Code Playgroud)
但在ghci,我得到了
parse error on input '='
Run Code Online (Sandbox Code Playgroud)
我怎么能在GHCi中做到这一点?使用模式匹配('|')的事实会改变吗?
md2*_*rpe 17
查看使用警卫的语法:
bar x y | x == 0 = 0
| y == 0 = 0
| otherwise = x * y
Run Code Online (Sandbox Code Playgroud)
写在GHCi的一行:
let bar x y | x == 0 = 0 | y == 0 = 0 | otherwise = x * y
Run Code Online (Sandbox Code Playgroud)
And*_*ewC 11
使用文件
不要将代码直接输入ghci,除非它真的是一行代码.
将代码保存在名为PatternMatch.hs的文本文件中,并通过键入将其加载到ghci中.
:l PatternMatch.hs
Run Code Online (Sandbox Code Playgroud)
然后,如果您进行更改(并保存),您可以通过键入来重新加载ghci中的文件
:r
Run Code Online (Sandbox Code Playgroud)
或者,你可以在他们所在的练习之后命名你的文件,或者如果它真的是一次性代码,只需要重新安装Temp.hs.
通过在文本文件中保存内容,您可以更轻松地编辑和重用它.
模块
稍后您将使用适当的模块一起收集相关功能,因此他们可以导入到其他程序中.例如,你可以拥有
module UsefulStuff where
pamf = flip fmap
Run Code Online (Sandbox Code Playgroud)
保存在名为UsefulStuff.hs的文件中,然后保存在另一个文件中
import UsefulStuff
Run Code Online (Sandbox Code Playgroud)
然后使用UsefulStuff中的函数.
模块对于你现在正在做的事情来说是过度的,但是获得编辑,保存,重新编译,测试,重复的工作流程,你将从相当多的努力中省去.