单子脱糖 haskell
monadic desugaring haskell
正在阅读有关现实世界中 monad 的章节 Haskell。我遇到了 do 符号的脱糖,特别是当我们有类似 pattern <- action
.
的时候
-- file: ch14/Do.hs
doNotation3 =
do pattern <- act1
act2
{- ... etc. -}
actN
上面的例子脱糖后变成:
-- file: ch14/Do.hs
translated3 =
let f pattern = do act2
{- ... etc. -}
actN
f _ = fail "..."
in act1 >>= f
我无法理解您如何在一个 let 子句中有两个模式匹配案例?
我不明白你怎么能在同一个 let 子句中包含 f pattern
和 f _
。我尝试查找 let 子句中是否可以有多个模式匹配,但据我所知,大多数人使用 case 语句来做到这一点。
我需要一些帮助来理解这里到底发生了什么?
I am having trouble understanding is how you can have two pattern matching cases in a let clause?
嗯,你可以:
example :: Int -> Int
example n =
let f 0 = 1
f x = x * f (x - 1)
in f n
记住,这是一个 let … in…
表达式,而不是 do
的 let
。对于此类表达式中的所有绑定,(几乎)适用与您常用的顶级表达式相同的规则,例如你可以使用模式匹配。
如果将其转换为 where
:
可能会更容易一些
example :: Int -> Int
example n = f n
where
f 0 = 1
f x = x * f (x - 1)
正在阅读有关现实世界中 monad 的章节 Haskell。我遇到了 do 符号的脱糖,特别是当我们有类似 pattern <- action
.
-- file: ch14/Do.hs
doNotation3 =
do pattern <- act1
act2
{- ... etc. -}
actN
上面的例子脱糖后变成:
-- file: ch14/Do.hs
translated3 =
let f pattern = do act2
{- ... etc. -}
actN
f _ = fail "..."
in act1 >>= f
我无法理解您如何在一个 let 子句中有两个模式匹配案例?
我不明白你怎么能在同一个 let 子句中包含 f pattern
和 f _
。我尝试查找 let 子句中是否可以有多个模式匹配,但据我所知,大多数人使用 case 语句来做到这一点。
我需要一些帮助来理解这里到底发生了什么?
I am having trouble understanding is how you can have two pattern matching cases in a let clause?
嗯,你可以:
example :: Int -> Int
example n =
let f 0 = 1
f x = x * f (x - 1)
in f n
记住,这是一个 let … in…
表达式,而不是 do
的 let
。对于此类表达式中的所有绑定,(几乎)适用与您常用的顶级表达式相同的规则,例如你可以使用模式匹配。
如果将其转换为 where
:
example :: Int -> Int
example n = f n
where
f 0 = 1
f x = x * f (x - 1)