静态指针的二进制实例

时间:2018-01-31 22:32:37

标签: haskell cloud-haskell

我有以下数据类型

data Foo a b = A (StaticPtr (a -> b)) deriving (Generic, Typeable)

我想为这种类型生成Binary实例,所以我可以在远程节点上使用这个函数。

但是,使用自动二进制实例化并不起作用:

instance (Binary a, Binary b) => Binary (Foo a b)

这导致

• Could not deduce (Binary (StaticPtr (a -> b)))
    arising from a use of ‘binary-0.8.5.1:Data.Binary.Class.$dmput’
  from the context: (Binary a, Binary b)
    bound by the instance declaration
    at /Users/abhiroop/Haskell/snape/app/Spec.hs:23:10-49
• In the expression:
    binary-0.8.5.1:Data.Binary.Class.$dmput @Foo a b
  In an equation for ‘binary-0.8.5.1:Data.Binary.Class.put’:
      binary-0.8.5.1:Data.Binary.Class.put
        = binary-0.8.5.1:Data.Binary.Class.$dmput @Foo a b
  In the instance declaration for ‘Binary (Foo a b)’


• Could not deduce (Binary (StaticPtr (a -> b)))
    arising from a use of ‘binary-0.8.5.1:Data.Binary.Class.$dmget’
  from the context: (Binary a, Binary b)
    bound by the instance declaration
    at /Users/abhiroop/Haskell/snape/app/Spec.hs:23:10-49
• In the expression:
    binary-0.8.5.1:Data.Binary.Class.$dmget @Foo a b
  In an equation for ‘binary-0.8.5.1:Data.Binary.Class.get’:
      binary-0.8.5.1:Data.Binary.Class.get
        = binary-0.8.5.1:Data.Binary.Class.$dmget @Foo a b
  In the instance declaration for ‘Binary (Foo a b)’

如何在此处自动生成Binary个实例?

2 个答案:

答案 0 :(得分:3)

您可以通过staticKeyStaticPtr序列化为Fingerprint,并通过其下方的unsafeLookupStaticPtr对其进行反序列化。

您无法为Binary定义StaticPtr实例(即使您将其包装在newtype中以避免孤儿),因为查找不能完全执行。但您仍然可以将序列化程序和反序列化程序定义并用作常规的非重载函数。

答案 1 :(得分:1)

夏丽娅的回答是正确的。但是我通常需要更改我的数据类型以远程传递它们。我在这里写我的更改所以如果有人想远程发送一个函数可能会有用,这个在线资源不多。

所以没有

data Foo a b = A (StaticPtr (a -> b))

我已将数据类型更改为如下所示:

data Foo a b = A (a -> b)

或简化

data Foo f = A f

此处f是我想远程发送的功能。

所以举一个像(+ 1)这样的函数的简单例子,想象一下我想把它映射到远程存在的列表[1,2,3]上。我的代码变成这样:

main :: IO [Int]
main = do
let list = [1,2,3]
    a = static (A (+ 1)) :: StaticPtr (Foo (Int -> Int))
    t = staticKey a
    -- assuming you sent t to the remote node
    -- code on the remote node
    x <- unsafeLookupStaticPtr t
    case x of
      Just sptr -> case deRefStaticPtr sptr of
                         A f -> return $ map f list
                         _   -> error "Task undefined"
      Nothing -> error "Wrong function serialized"