gpt4 book ai didi

haskell - 模式匹配 Haskell 中的 Number

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

我有一个函数需要一个 Num并根据它是浮点数、 double 数还是整数来做不同的事情。我发现这样做的唯一方法是使用类型类,但这看起来很丑陋。有没有办法匹配任何类型的数字,所以根据 Num 的 3 个实例中的哪一个来做不同的事情?就像是

myFun :: (Num a) => a -> T
myFun n = case n of
n :: Int -> something for ints
n :: Float -> something for floats
n :: Double -> something for doubles

而不是
class MyClass a where
myFun :: (Num a) => a -> T

带有 Int 的实例, Float , Double ?

最佳答案

根据我的阅读,这是类型类的教科书应用:

module Main where

class Num a => Funnable a where
myFun :: a -> a

instance Funnable Int where
myFun = id

instance Funnable Float where
myFun = (+ 2)

instance Funnable Double where
myFun = (+ 1)

main :: IO ()
main = do
print $ myFun (1 :: Int)
print $ myFun (1 :: Float)
print $ myFun (1 :: Double)

给出:
$ stack exec example
1
3.0
2.0

如果使用不当,类型类还会为您提供编译时类型错误。例如,假设我们跳过了 Double 的实例声明。 :
src/Main.hs:14:13: error:
• No instance for (Funnable Double) arising from a use of ‘myFun’
• In the second argument of ‘($)’, namely ‘myFun (1 :: Double)’
In a stmt of a 'do' block: print $ myFun (1 :: Double)
In the expression: do { print $ myFun (1 :: Double) }

关于haskell - 模式匹配 Haskell 中的 Number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40085547/

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