Haskell中函数的序列化 [英] Serialization of functions in Haskell
本文介绍了Haskell中函数的序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以在Haskell中序列化(读取/显示)函数?例如,给出:
:t(+1)
(+1):: Num a => a - > a
我希望能有这样的东西:
读取(+1):: Num a => a - > a
不幸的是,这会抛出一个错误:
无法推断(读取(a - > a))由上下文(数字a)
使用读取
引起类型签名:Num a => a - > a
at< interactive> 1:1-30
可能的修正:
add(读取(a - > a))到
的上下文中表达式类型签名:Num a => a - > a
或者添加一个实例声明(Read(a - > a))
在表达式中:read(+1):: Num a => a - > a
在'it'的等式中:it = read(+1):: Num a => a - > a
解决方案
您可以使用 plugins 包在运行时读取代码。正如augustss所说,显示是不可能的。
一个可以如何使用的例子:
import System.Eval.Haskell
main = do
mf< - eval(+1):: Int - > Int[]
案例mf of
只需f - > print $(f :: Int - > Int)0
_ - > putStrLn由于某些原因无法评估。:(
Is there a way to serialize (read/show) functions in Haskell?
For example given that:
:t (+1)
(+1) :: Num a => a -> a
I wish to be able to have something like:
read "(+1)" :: Num a => a -> a
Unfortunately this throws an error:
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
解决方案
You could use something like the plugins package to read code at runtime. Showing is, as augustss says, impossible though.
An example of how it could be used:
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. :("
这篇关于Haskell中函数的序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文