[英]Anonymous function without parameter in Haskell
Could I define an anonymous function without parameter in Haskell? 我可以在Haskell中定义不带参数的匿名函数吗?
I have a block of code repeated in several branches. 我在几个分支中重复了一段代码。 Those code refer to several values outside. 这些代码引用了多个外部值。
Purpose 0: Define a function do the job in the codeBlock. 用途0:在codeBlock中定义一个功能来完成这项工作。
Purpose 1: Don't repeat codeBlock twice. 目的1:不要重复两次codeBlock。
Purpose 2: Don't pass d1..d4 to the function. 目的2:不要将d1..d4传递给函数。 Avoid passing file and time even better. 避免更好地传递文件和时间。
f event d1 d2 d3 d4 =
case event of
(Modified file time) -> do
codeBlock file time d1 d2 d3 d4
(Added file time) -> do
codeBlock file time d1 d2 d3 d44
_ -> return ()
There is no such thing as a function without parameters (anonymous or otherwise). 没有没有参数的函数(匿名或其他)。 That's just a value (and in Haskell, actions like main :: IO ()
are also just values). 这只是一个值 (和在Haskell,像行为 main :: IO ()
也只是值)。
For sure, a value can be defined anywhere (like a function); 当然,可以在任何地方定义一个值(如函数)。 however if you want to reuse it in more than one place you should not make it anonymous but give it a (locally scoped) name: 但是,如果您想在多个地方重用它, 则不应将其设为匿名,而应使用(本地范围)名称:
f event d1 d2 d3 d4 =
case event of
(Modified file time) -> do
defaultAction time
(Added file time) -> do
defaultAction time
_ -> return ()
where defaultAction time = do
codeBlock file time d1 d2 d3 d4
BTW, do
blocks with only a single statement are equivalent to just that statement alone, ie you could also write 顺便说一句,只用一个语句do
块就等于仅使用该语句,即,您也可以编写
f event d1 d2 d3 d4 =
case event of
(Modified file time) -> defaultAction time
(Added file time) -> defaultAction time
_ -> return ()
where defaultAction time = codeBlock file time d1 d2 d3 d4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.