我工作的HList實施異構數據結構,我堅持努力實現map
功能吧。我已經嘗試了很多不同的方法,但是每次都遇到與該函數相關的編譯器錯誤。映射了一個通用的功能
以下是我要如何使用通用功能Just
,將其應用到輸入數據結構中的所有元素的例子。
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
-- | An input heterogenous data structure
recursivePairs :: (Int, (Char, (Bool,())))
recursivePairs = (1, ('a', (True,())))
-- | This is how I want to use it
recursivePairs' :: (Maybe Int, (Maybe Char, (Maybe Bool,())))
recursivePairs' = hMap Just recursivePairs
class HMap f input output where
hMap :: f -> input -> output
-- | A counterpart of a Nil pattern match for a list
instance HMap f()() where
hMap _ _ =()
-- | A counterpart of a Cons pattern match for a list
instance
(HMap f iTail oTail,
Apply f iHead oHead) =>
HMap f (iHead, iTail) (oHead, oTail)
where
hMap f (head, tail) = (apply f head, hMap f tail)
class Apply f input output where
apply :: f -> input -> output
instance Apply (input -> output) input output where
apply = id
有了這個,我發現了以下編譯器錯誤:
No instance for (Apply (a0 -> Maybe a0) Int (Maybe Int))
arising from a use of `hMap'
The type variable `a0' is ambiguous
有沒有在所有的方式來解決這一點,如果沒有的話,爲什麼?
我認爲這個問題是該類型系統不會意識到你正在實例化'Just'不同的具體類型上的每個連續的申請,因爲您'hMap'的定義不斷重複使用相同的'F'。第一次應用它時,類型是'Int - > Maybe Int',第二次應用它時,類型是'Char - > Maybe Char'。不過,我仍然不確定如何解決這個問題。 – 2013-04-06 23:00:40
@GabrielGonzalez 是的,這也正是問題。如果你添加一個fundep'|輸入輸出 - > F'到'Apply'類,錯誤消息會說,它正在尋找的情況下,像'(BOOL - >也許布爾)字符(字符也許)'。我正在考慮使用['cast'](http://hackage.haskell。org/packages/archive/base/latest/doc/html/Data-Typeable.html#v:cast)在類型級別斷開'f'的兩個用法,但這並不是很自然,取決於「Typeable」也不是很誘人。 – 2013-04-07 18:48:38