gpt4 book ai didi

haskell - 在 Haskell 中表达一般计算的惯用方式

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

必须存在一种良好的惯用方式来在类型级别上表达 Haskell 中的通用计算。我能想到的就是这个(非法的)面向对象的模仿。

class Computation where
compute :: Computation -> Double -> Double

data Id = Id
instance Computation Id where
compute _ = id

data Square a = Computation a => Square a
instance Computation (Square a) where
compute (Square underlying) x = sqr $ compute underlying x where square x = x*x

data Scale a = Computation a => Scale a Double
compute (Scale underlying c) x = c * compute underlying x

理想情况下,我希望保持开放性,所以this方法对我没有吸引力。我的要求是不是太高了?

最佳答案

您当然可以使用您所拥有的方法来做到这一点,您只需要正确地获取语法和一些细节,但这确实有效:

class Computation a where
compute :: a -> Double

instance Computation Double where
compute = id

data Square a = Square a

instance Computation a => Computation (Square a) where
compute (Square underlying) = square $ compute underlying where square i = i * i

data Scale a = Scale a Double

instance Computation a => Computation (Scale a) where
compute (Scale underlying c) = c * compute underlying

data Add a = Add a Double

instance Computation a => Computation (Add a) where
compute (Add underlying c) = c + compute underlying

test :: Add (Scale (Scale (Square Double)))
test = Add (Scale (Scale (Square 2) 5) 0.5) 100

main :: IO ()
main = print $ compute test

请注意,我必须为 Double 添加一个 Computation 实例,它只是 consttest 表达式应该等于 (((2^2) * 5) * 0.5) + 100,并且确实比较这两个结果我得到了相同的值。

不过,我并不完全确定这就是您想要的方法。这也并不真正等同于您发布的链接中显示的方法,使用这种编码表达变量将非常困难,因为没有好的方法可以输入所有变量值的映射来减少表达式。

关于haskell - 在 Haskell 中表达一般计算的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25255289/

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