這並不工作,但我認爲這是足夠有趣反正分享到:
{-#LANGUAGE GADTs #-}
data Poly a where
Poly :: [b] -> Poly [b]
我們現在有一個型Poly這是參數上a
,但有效a
必須是一個列表:
~% ghci Poly.hs
GHCi, version 6.8.2: http://www.haskell.org/ghc/ :? for help
Loading package base ... linking ... done.
[1 of 1] Compiling Main (Poly.hs, interpreted)
Ok, modules loaded: Main.
*Main> :k Poly
Poly :: * -> *
*Main> :t Poly
Poly :: [b] -> Poly [b]
*Main> case Poly [1,2,3] of _ -> 0
0
*Main> case Poly 4 of _ -> 0
<interactive>:1:10:
No instance for (Num [b])
arising from the literal `4' at <interactive>:1:10
Possible fix: add an instance declaration for (Num [b])
In the first argument of `Poly', namely `4'
In the scrutinee of a case expression: Poly 4
In the expression: case Poly 4 of _ -> 0
*Main> case Poly True of _ -> 0
<interactive>:1:10:
Couldn't match expected type `[b]' against inferred type `Bool'
In the first argument of `Poly', namely `True'
In the scrutinee of a case expression: Poly True
In the expression: case Poly True of _ -> 0
現在我們可以試着寫的Functor
的實例,該類型:
instance Functor Poly where
fmap f (Poly x) = Poly (f x)
Couldn't match expected type `[b1]' against inferred type `b2'
`b2' is a rigid type variable bound by
the type signature for `fmap' at <no location info>
In the first argument of `Poly', namely `(f x)'
In the expression: Poly (f x)
In the definition of `fmap': fmap f (Poly x) = Poly (f x)
這不起作用。有趣的是,我們甚至不能真正寫myMap
:
polymap f (Poly x) = Poly (f x)
如果我們試試這個,我們得到
GADT pattern match in non-rigid context for `Poly'
Tell GHC HQ if you'd like this to unify the context
In the pattern: Poly x
In the definition of `polymap': polymap f (Poly x) = Poly (f x)
當然,我們可以用一個類型標註修復:
polymap :: ([a] -> [b]) -> Poly [a] -> Poly [b]
但沒有它,這與fmap有什麼相似的問題。 Functor只是沒有任何地方可以擺脫這個額外的「我保證總是使用列表」的內容,而且它確實不能。例如,您總是可以說undefined :: Poly Int
。總之,我不認爲有這樣一個成語可以表達這一點(實際上,有人可能會用足夠的ghc擴展魔術來做到這一點)。當然不是現有的。
你想要'fmap(take 3)polynomial'做什麼?我根本沒有意義。 - 'polynomial'只是一個多項式:: Poly CoeffType'' polynomial = Poly [a 1,a 2 ..]'? – leftaroundabout
@leftaroundabout:我給出了一些示例代碼。 – Xodarap
由於這不是一個真正的規範操作(類型類應該如何知道它是一個列表,而不是一個數組),我根本不會讓它成爲任何實例。我也不會稱之爲「some-'map'」而是「coeffsTransform」或類似的東西。 – leftaroundabout