gpt4 book ai didi

haskell - 我如何使用没有 case-of 的守卫重写这个 Haskell?

转载 作者:行者123 更新时间:2023-12-02 10:54:45 25 4
gpt4 key购买 nike

下面列出了一个函数的三个版本。 #2 和 #3 有效。 #2 将是我现在的第一选择。我想找到一些方法让#1 发挥作用,并看看它的比较如何。它在底部。

首先,我有这种类型:

data Value =
IntVal Int
| BoolVal Bool
deriving (Show)

这个函数(一个的工作片段):

-- #2
evaluate (If ec et ef) s0 =
case vc of
(IntVal ____) -> error "Conditional expression in If statement must be a boolean"
(BoolVal vcb) -> if vcb then (vt, st)
else (vf, sf)
where (vc, sc) = evaluate ec s0
(vt, st) = evaluate et sc
(vf, sf) = evaluate ef sc

我想知道是否可以去掉 case 语句并使用 guard 代替。我可以在 case 语句中使用守卫,我发现这有效:

-- #3
evaluate (If ec et ef) s0 =
case vc of
(IntVal _) -> error "Conditional expression in If statement must be a boolean"
(BoolVal vcb) | vcb -> (vt, st)
| otherwise -> (vf, sf)
where (vc, sc) = evaluate ec s0
(vt, st) = evaluate et sc
(vf, sf) = evaluate ef sc

很高兴知道这一点。我认为#2 最清楚地表达了我的意图。尽管如此,这是我尝试的第一件事,我想弄清楚它实际上是如何工作的:

-- #1
evaluate (If ec et ef) s0
| (IntVal vc) = error "Conditional expression in If statement must be a boolean"
| vc == True = (vt, st)
| otherwise = (vf, sf)
where (vc, sc) = evaluate ec s0
(vt, st) = evaluate et sc
(vf, sf) = evaluate ef sc

这会出现以下错误。看来我需要一些东西来询问 Value 类型的某些内容是否也是 IntVal 子类型?:

Couldn't match expected type `Int' with actual type `Value'
In the first argument of `IntVal', namely `vc'
In the expression: (IntVal vc)

--------------------------------------------------------------------------------

Couldn't match expected type `Bool' with actual type `Value'
In the expression: (IntVal vc)
In a stmt of a pattern guard for
an equation for `evaluate':
(IntVal vc)

如何修复这些错误并实现无案例、仅防护的实现?

最佳答案

这并不是一个真正的答案,但我会把整个事情写成这样:

evaluate (If ec et ef) s0 =
case evaluate ec s0 of
(True, sc) -> evaluate et sc
(False, sc) -> evaluate ef sc

我发现 vtstvfsf 的命名更难阅读,因为我必须自己跟踪这些变量的数据流。不命名它们可以简化理解。

关于haskell - 我如何使用没有 case-of 的守卫重写这个 Haskell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25986068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com