gpt4 book ai didi

haskell - 该函数的正确类型声明是什么?

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

以下函数将不会加载:

charName :: a -> String
charName 'a' = "Alpha"
charName 'b' = "Bravo"
charName 'c' = "Charlie"
charName 'd' = "Delta"
charName 'e' = "Echo"
charName 'f' = "Foxtrot"
charName 'g' = "Golf"
charName 'h' = "Hotel"
charName 'i' = "India"
charName 'j' = "Juliet"
charName 'k' = "Kilo"
charName 'l' = "Lima"
charName 'm' = "mike"
charName 'n' = "November"
charName 'o' = "Oscar"
charName 'p' = "Papa"
charName 'q' = "Quebec"
charName 'r' = "Romeo"
charName 's' = "Sierra"
charName 't' = "Tango"
charName 'u' = "Uniform"
charName 'v' = "Victor"
charName 'w' = "Whiskey"
charName 'x' = "X-ray"
charName 'y' = "Yankee"
charName 'z' = "Zulu"
charName 0 = "Zero"
charName 1 = "One"
charName 2 = "Two"
charName 3 = "Three"
charName 4 = "Four"
charName 5 = "Five"
charName 6 = "Six"
charName 7 = "Seven"
charName 8 = "Eight"
charName 9 = "Nine"
charName x = ""

它给了我以下错误:

[1 of 1] Compiling Main ( baby.hs, interpreted )

baby.hs:41:9: Couldn't match expected type a' against inferred typeChar' a' is a rigid type variable bound by
the type signature for
charName' at baby.hs:40:12 In the pattern: 'a' In the definition of `charName': charName 'a' = "Alpha"

baby.hs:67:9: No instance for (Num Char) arising from the literal 0' at baby.hs:67:9
Possible fix: add an instance declaration for (Num Char)
In the pattern: 0
In the definition of
charName': charName 0 = "Zero" Failed, modules loaded: none.

不知道如何让它发挥作用。有人有什么想法吗?

最佳答案

使用新的数据类型

将 Char 或 Int 作为函数参数传递的简单方法是定义一个新的数据类型来封装它们:

data (Num a) => CharOrNum a = C Char | N a

charName (C 'z') = "Zulu"
charName (N 0) = "Zero"

然后你就可以像这样使用它

ghci> charName $ C 'z'
"Zulu"
ghci> charName $ N 0
"Zero"

通过此更改,charName 的类型为 (Num t) => CharOrNum t -> [Char]

使用新类型类

另一种方法是为两种参数类型定义一个公共(public)类型类,例如 Show

class Nameable a where
nameit :: a -> String

instance Nameable Char where
nameit 'z' = "Zulu"
nameit _ = ""

instance Nameable Integer where
nameit 0 = "Zero"
nameit _ = ""

然后你可以像这样使用它:

ghci> (nameit 0, nameit 'z')
("Zero","Zulu")

关于haskell - 该函数的正确类型声明是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3246400/

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