Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回类型构造函数的haskell类型签名_Haskell_Types_Constructor_Return Type - Fatal编程技术网

返回类型构造函数的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
具有type
a->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)