gpt4 book ai didi

haskell - 我如何概括 Maybe 和 Either 的违约行为?

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

在 Haskell 中,如果我有两个这样的函数:

defEither ∷   Either l r → r → r
defEither eith defVal = either (const defVal) id eith

defMaybe ∷   Maybe a → a → a
defMaybe m d = fromMaybe d m

如何编写一个类型类(或类似效果的东西),以便我可以在 Either 和 Maybe 之间概括“可默认”的概念?

类似的东西

class Defaultable ???? where
def ∷ a b → b → b

最佳答案

事实证明,为 Either 创建实例的语法让我感到困惑。

这是我完成的:

class Defaultable a where
def ∷ a b → b → b

instance Defaultable (Either m) where
def e d = either (const d) id e

instance Defaultable Maybe where
def m d = fromMaybe d m
<小时/>

还有一些测试

def (Just 1) 2
>> 1

def Nothing 2
>> 2

def (Right 2) 5
>> 2

def (Left 3) 5
>> 5

def (Left "Arrghh") 5
>> 5

关于haskell - 我如何概括 Maybe 和 Either 的违约行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34835713/

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