在Haskell中是否存在非递归绑定的语法,就像`let`和`let rec`在类似语言中的区别? [英] is there any syntax for non-recursive binding in Haskell, just like the difference between `let` and `let rec` in similar languages?
问题描述
非递归绑定允许我限制绑定值,例如:
Non-recursive binding allows me to shadow bound value, for instance:
b a = let norec a = a + 10 in a
这里让norec
意味着 let
绑定但不能递归。
here let norec
created by myself means a let
binding but not recursive.
使用记录通配符时非常有用:
This is extremely helpful when using record wildcards:
data MyRecord = MyRecord{ {- vary huuuuuge set of definitions -} }
foo MyRecord{..} = let norec field1 = field1 + 1
field2 = modify field2
{- some other modifications to the fields -}
in MyRecord{..}
可以实现吗?或者你如何处理你的情况?
Is that achievable? Or how do you deal with it in your cases?
推荐答案
实际上记录通配符在这里有用吗?通常的做事方式对我来说看起来相当简洁:
Are record wildcards actually that useful here? The usual old way of doing things looks quite concise to me:
foo r = r { field1 = field1 r + 1, field2 = modify (field2 r) }
直接回答你的问题是没有非递归Haskell中的 let
的模拟;尽管你可以使用 Identity
monad来排序:
The direct answer to your question is that there is no non-recursive analog of let
in Haskell; though you can use the Identity
monad to sort of hack something into place:
foo MyRecord{..} = runIdentity $ do
field1 <- return (field1 + 1)
field2 <- return (modify field2)
return MyRecord{..}
这篇关于在Haskell中是否存在非递归绑定的语法,就像`let`和`let rec`在类似语言中的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!