gpt4 book ai didi

haskell - 如何从 "add"类 "Add"打印函数 "Fun with Type Functions"的结果

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

下面的代码来自这里 Fun with Type Functions

{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, TypeFamilies #-}

-- Start basic
class Add a b where
type SumTy a b
add :: a -> b -> SumTy a b

instance Add Integer Double where
type SumTy Integer Double = Double
add x y = fromIntegral x + y

instance Add Double Integer where
type SumTy Double Integer = Double
add x y = x + fromIntegral y

instance (Num a) => Add a a where
type SumTy a a = a
add x y = x + y
-- End basic

这是我要运行的代码:

main = print $ show (add 1 1)

这是结果:

No instance for (Show (SumTy a0 b0))
arising from a use of `show'
Possible fix: add an instance declaration for (Show (SumTy a0 b0))
In the second argument of `($)', namely `show (add 1 1)'
In the expression: print $ show (add 1 1)
In an equation for `main': main = print $ show (add 1 1)

我已经尝试过一些方法,例如将“数据”放在各处:

结果 1

Not a data constructor: `a'

结果 2(删除“instance (Num a)”后)

Multiple declarations of `Double'
Declared at: ...

比如添加一些功能:

class Add a b where
type SumTy a b
add :: a -> b -> SumTy a b
s :: SumTy a b -> String

instance Add Integer Double where
type SumTy Integer Double = Double
add x y = fromIntegral x + y
s (SumTy _ x) = show x

main = print $ show (s (add 1 2.0) )

结果是:

Not in scope: data constructor `SumTy'

您可能已经注意到我被困住了,所以任何帮助对我来说都是无价的。 :)

最佳答案

问题是没有足够的上下文来确定要使用哪个 Add 实例,因此无法确定结果的类型。由于 ghc 不知道要使用哪些类型,它报告了最普遍的问题,没有针对一般 SumTy a bShow 实例:

No instance for (Show (SumTy a0 b0))
arising from a use of `show'
Possible fix: add an instance declaration for (Show (SumTy a0 b0))
In the second argument of `($)', namely `show (add 1 1)'
In the expression: print $ show (add 1 1)
In an equation for `main': main = print $ show (add 1 1)

不过,建议的“可能的修复”并不是这里所需要的。您需要指定要添加的参数类型add,以便确定要使用的实例,从而确定结果类型:

*TyFun> show (add (1 :: Int) (1 :: Int))
"2"
*TyFun> show (add (1 :: Integer) (1 :: Integer))
"2"
*TyFun> show (add (1 :: Integer) (1 :: Double))
"2.0"
*TyFun> show (add (1 :: Integer) (1 :: Float))

<interactive>:7:1:
No instance for (Show (SumTy Integer Float))
arising from a use of `show'
Possible fix:
add an instance declaration for (Show (SumTy Integer Float))
In the expression: show (add (1 :: Integer) (1 :: Float))
In an equation for `it':
it = show (add (1 :: Integer) (1 :: Float))

<interactive>:7:7:
No instance for (Add Integer Float) arising from a use of `add'
Possible fix: add an instance declaration for (Add Integer Float)
In the first argument of `show', namely
`(add (1 :: Integer) (1 :: Float))'
In the expression: show (add (1 :: Integer) (1 :: Float))
In an equation for `it':
it = show (add (1 :: Integer) (1 :: Float))

关于haskell - 如何从 "add"类 "Add"打印函数 "Fun with Type Functions"的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14468782/

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