Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization of functions in Haskell

Tags:

haskell

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
like image 263
Roskoto Avatar asked Aug 03 '11 12:08

Roskoto


2 Answers

It's (in general) impossible to show a function, but reading one is possible in principle if you have a Haskell compiler available at runtime.

like image 106
augustss Avatar answered Oct 16 '22 02:10

augustss


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. :("
like image 34
valderman Avatar answered Oct 16 '22 03:10

valderman