Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to a Type Constructor in Haskell

Does anyone know if there's a function in Haskell which does something like this:

"Int" -> Int

"String" -> String

"Bool" -> Bool

ie. it takes a string representation of a type constructor name, and converts it to the actual type constructor, both in an expression and in a pattern.

edit: My overall goal is to simplify something like:

transExp (Add exp1 exp2) vars
  = transExp exp1 vars ++ transExp exp2 vars ++ [IAdd]

transExp (Sub exp1 exp2) vars
  = transExp exp1 vars ++ transExp exp2 vars ++ [ISub]

Into a single pattern match, so basically convert Add or Sub to a string, add an "I" to the front, and convert it back to a type.

like image 467
Jack Avatar asked Nov 17 '11 10:11

Jack


2 Answers

There is a much better way to refactor your code here without any Template Haskell or reflection shenanigans by simply joining your Add and Sub cases into one:

data BinOp = Add | Sub | ...

data Expr = ...
          | BinOp BinOp Expr Expr
          | ...

transExp (BinOp op exp1 exp2) vars
    = transExp exp1 vars ++ transExp exp2 vars ++ [transOp op]
...

transOp Add = IAdd
transOp Sub = ISub

This way, we're using the data type to express directly the fact that binary operators are related, and therefore have similar translations. You can still pattern match on BinOp Add exp1 exp2 if you want to make a special case for addition somewhere.

like image 142
hammar Avatar answered Nov 16 '22 01:11

hammar


In which context? There is Template Haskell and Data.Typeable, but for an actually helpful answer you need to provide more details.

like image 3
Landei Avatar answered Nov 16 '22 01:11

Landei