Haskell中函数的序列化

时间:2011-08-03 12:03:38

标签: haskell

有没有办法在Haskell中序列化(读/显示)函数?

例如,鉴于:

:t (+1) 
(+1) :: Num a => a -> a

我希望能够有类似的东西:

read "(+1)" :: Num a => a -> a

不幸的是,这会引发错误:

Could not deduce (Read (a -> a)) arising from a use of `read'
from the context (Num a)
  bound by an expression type signature: Num a => a -> a
  at <interactive>:1:1-30
Possible fix:
  add (Read (a -> a)) to the context of
    an expression type signature: Num a => a -> a
  or add an instance declaration for (Read (a -> a))
In the expression: read "(+1)" :: Num a => a -> a
In an equation for `it': it = read "(+1)" :: Num a => a -> a

2 个答案:

答案 0 :(得分:10)

(通常)不可能显示函数,但如果在运行时有Haskell编译器,原则上可以读取一个函数。

答案 1 :(得分:7)

您可以使用plugins包之类的东西在运行时读取代码。正如奥古斯特所说,显示是不可能的。

如何使用它的一个例子:

import System.Eval.Haskell

main = do
  mf <- eval "(+1) :: Int -> Int" []
  case mf of
    Just f -> print $ (f :: Int -> Int) 0
    _      -> putStrLn "Couldn't eval for some reason. :("