gpt4 book ai didi

haskell - Haskell 中的模式匹配数据类型。捷径?

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

在下面的 Haskell 代码中,如何写得更简洁?是否有必要列出所有四个条件,或者可以用更紧凑的模式来概括这些条件?例如,有没有一种方法可以利用 Haskell 已经知道如何添加 float 和整数,而无需手动指定 fromIntegral

data Signal = SignalInt Int | SignalFloat Float | Empty deriving (Show)

sigAdd :: Signal -> Signal -> Signal
sigAdd (SignalInt a) (SignalInt b) = SignalInt (a + b)
sigAdd (SignalInt a) (SignalFloat b) = SignalFloat ((fromIntegral a) + b)
sigAdd (SignalFloat a) (SignalInt b) = SignalFloat (a + (fromIntegral b))
sigAdd (SignalFloat a) (SignalFloat b) = SignalFloat (a + b)

main :: IO ()
main = do
putStrLn (show (sigAdd (SignalFloat 2) (SignalInt 5)))

最佳答案

Haskell 知道如何添加FloatInt;它对于类型非常具体和明确:

Prelude> (5 :: Int) + 3.5

<interactive>:1:13:
No instance for (Fractional Int)
arising from the literal `3.5' at <interactive>:1:13-15
Possible fix: add an instance declaration for (Fractional Int)
In the second argument of `(+)', namely `3.5'
In the expression: (5 :: Int) + 3.5
In the definition of `it': it = (5 :: Int) + 3.5

定义一个函数toFloatSig:

toFloatSig (SignalInt a) = fromIntegral a
toFloatSig (SignalFloat a) = a

然后你可以写:

sigAdd (SignalInt a) (SignalInt b) = SignalInt (a + b)
sigAdd sa sb = SignalFloat (toFloatSig sa + toFloatSig sb)

Signal 设为 Num class 的实例也可能是合适的。 ,以便您可以直接使用 + 运算符添加它们。另外,您可以使类型更通用:

data (Num a) => Signal a = Signal a | Empty deriving (Show)

关于haskell - Haskell 中的模式匹配数据类型。捷径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1715871/

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