यह काम नहीं करता है, लेकिन मैंने सोचा कि यह काफी दिलचस्प वैसे भी साझा करने के लिए किया गया था:
{-#LANGUAGE GADTs #-}
data Poly a where
Poly :: [b] -> Poly [b]
अब हम एक प्रकार पाली कि 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 था। "मैं हमेशा सूचियों का उपयोग करने का वादा करता हूं" के इस अतिरिक्त संदर्भ के लिए फंक्टर के पास कहीं भी नहीं है, और वास्तव में यह वास्तव में नहीं हो सकता है। उदाहरण के लिए आप हमेशा undefined :: Poly Int
कह सकते हैं। संक्षेप में, मुझे नहीं लगता कि वास्तव में एक मुहावरे है जो इसे व्यक्त कर सकता है (असल में, कोई शायद ऐसा करने के लिए पर्याप्त ghc एक्सटेंशन जादू के साथ आएगा)। निश्चित रूप से एक मौजूदा नहीं है।
आप क्या चाहते हैं 'fmap (3) बहुपद' करना चाहते हैं? यह मुझे बिल्कुल समझ में नहीं आता है। - 'बहुपद' बस एक बहुपद है :: पॉली CoeffType 'बहुपद = पॉली [ए₁, ए₂ ..]'? – leftaroundabout
@ बाएंअराउंडबाउट: मैंने कुछ उदाहरण कोड दिया है। – Xodarap
चूंकि यह वास्तव में एक कैननिकल ऑपरेशन नहीं है (टाइपक्लास को यह कैसे पता होना चाहिए कि यह एक सूची है और उदाहरण के लिए एक ऐरे नहीं), मैं इसे बिल्कुल भी उदाहरण नहीं दूंगा। मैं इसे "कुछ-'मैप' भी नहीं कहूंगा बल्कि बल्कि 'coeffstransform' या ऐसा कुछ भी कहूंगा। – leftaroundabout