返回类型构造函数的haskell类型签名
是否可以为此返回类型构造函数的haskell类型签名,haskell,types,constructor,return-type,Haskell,Types,Constructor,Return Type,是否可以为此getConstructor函数提供类型签名? 该函数可以工作,但我找不到编写返回类型的方法 module Main where data Letter a = A a | B a | C String deriving (Show) -- getConstructor :: String -> (a -> Letter ?) -- <== getConstructor
getConstructor
函数提供类型签名?
该函数可以工作,但我找不到编写返回类型的方法
module Main where
data Letter a =
A a
| B a
| C String
deriving (Show)
-- getConstructor :: String -> (a -> Letter ?) -- <==
getConstructor x
| x == "a" = A
| x == "b" = B
| otherwise = C
main = print $ theType
where theType = (getConstructor "b") "its b!"
modulemain其中
数据字母a=
A
|B a
|C字符串
派生(显示)
--getConstructor::String->(a->Letter?)--我只是将您的代码输入GHCi,并要求它告诉我类型:
Prelude> :{
Prelude| data Letter a =
Prelude| A a
Prelude| | B a
Prelude| | C String
Prelude| deriving (Show)
Prelude| :}
Prelude> :{
Prelude| getConstructor x
Prelude| | x == "a" = A
Prelude| | x == "b" = B
Prelude| | otherwise = C
Prelude| :}
Prelude> :t getConstructor
getConstructor :: [Char] -> String -> Letter String
这是有意义的,因为它需要一个[Char]
(又称a字符串
——这是x
参数)并返回a
、B
和C
中的一个,它们是字母
的构造函数。作为构造函数,它们也是函数-在C
的情况下,类型显然是String->Letter a
,而a
和B
具有typea->Letter a
。由于这些都是getConstructor
的可能返回值,因此它们必须是相同的类型-发生这种情况的唯一方法是a
始终是String
。这为我们提供了getConstructor
的类型为String->(String->Letter String)
,这正是GHCi上面所说的(稍加修改)。让我们看看:
getConstructor x
| x == "a" = A
| x == "b" = B
| otherwise = C -- <= Let's inspect this line
使用这样的函数无法在运行时动态选择类型,因为在Haskell中,所有类型在编译时都是已知的。因此,它仅限于处理String
s
getConstructor :: String -> (String -> Letter String)