在 Haskell 中,我嘗試呼叫newtypes我已宣告的以下兩個。
為什么會這樣:
newtype CharList = CharList { get2CharList :: [Char] } deriving (Eq, Show)
ghci> CharList "some"
CharList {get2CharList = "some"}
當這不起作用時:
newtype Pair a b = Pair { createPair :: (a, b) } deriving (Eq, Show)
ghci> Pair 2 4
<interactive>:13:1: error:
* Couldn't match expected type: t0 -> t
with actual type: Pair a0 b0
* The function `Pair' is applied to two value arguments,
but its type `(a0, b0) -> Pair a0 b0' has only one
In the expression: Pair 2 4
In an equation for `it': it = Pair 2 4
* Relevant bindings include it :: t (bound at <interactive>:13:1)
它是否需要一個 Monad 才能像這里看到的那樣作業:Writer monad 及其型別宣告
然后我是否必須在呼叫newtype
此外,如果我想要 anewtype接受更多引數,例如 3,我該怎么做?
uj5u.com熱心網友回復:
newtypePair被宣告為包含(或包裝)一個值的元組,因此這是創建值所必須提供的:
ghci> Pair (2, 4)
Pair {createPair = (2,4)}
Pair您可以使用以下值從值中提取元組createPair:
ghci> createPair $ Pair (2, 4)
(2,4)
雖然型別被指定為Pair a b(不帶括號或逗號),但資料建構式需要一個元組。型別宣告在等號的左邊,資料建構式在右邊。
語法Pair (2, 4)只是完整資料建構式的簡寫,這也是可能的:
ghci> Pair { createPair = (2, 4) }
Pair {createPair = (2,4)}
您可以以相同的方式創建具有更多型別引數的包裝器:
newtype Triple a b c = T { getTriple :: (a, b, c) } deriving (Eq, Show)
這個例子還展示了一些可能有助于理解上述內容的東西。型別的名稱不必與資料建構式的名稱相同。這里,型別的名稱是Triple,而資料建構式的名稱是T。
Triple您使用資料建構式創建一個值T:
ghci> T (1, "foo", True)
T {getTriple = (1,"foo",True)}
該運算式的型別是:
ghci> :t T (1, "foo", True)
T (1, "foo", True) :: Num a => Triple a String Bool
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/532463.html
下一篇:Haskell串列的高階過濾函式
