gpt4 book ai didi

haskell - Bool 类 - 像 Num?

转载 作者:行者123 更新时间:2023-12-04 23:17:13 24 4
gpt4 key购买 nike

我有自己的类型:

data MyType = ...

现在,我想在 if 中使用这种类型的值.有可能实现吗?当然,此时我得到错误:
 Couldn't match expected type ‘Bool’ with actual type ‘MyType’

最佳答案

if的标准语义/then/else特定于 Bool .使用 GHC,可以使用 RebindableSyntax 更改标准语义。延期。引用文档:

...the -XRebindableSyntax flag causes the following pieces of built-in syntax to refer to whatever is in scope, not the Prelude versions:

  • Conditionals (e.g. if e1 then e2 else e3) means ifThenElse e1 e2 e3. However case expressions are unaffected.


这是我对所问问题的技术回答。

但是,我固执的回答是你不应该那样做。相反,写一个类型为 MyType -> Bool 的谓词;然后使用 if predicate myValue then ... else ... .这种明确的方式在我看来更加清晰和惯用;作为附带好处,它也更加灵活,因为您可以拥有许多不同类型的谓词,而不是将任何单个谓词提升到特殊状态。

关于haskell - Bool 类 - 像 Num?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37038454/

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