[Haskell-cafe] Reflection.Emit in Haskell

Bulat Ziganshin bulat.ziganshin at gmail.com
Thu Jan 17 17:39:02 EST 2008

Hello Cetin,

Friday, January 18, 2008, 12:52:27 AM, you wrote:
> As a .NET (C#/F#) programmer learning Haskell, I would love to know
> the best online sources about run-time compilation etc. like

hs-plugins (unix-only afair), and GHC-as-a-library

> Reflection.Emit in .NET. I am making heavy use of this .NET API to
> compile customized (regular-expressions-) FSAs at run-time and want
> to learn how I might achieve the same in Haskell. Book or online
> article references specific to this issue will be highly appreciated ^_^

it was Runtime_Compilation page on old Haskell wiki, written by Andrew
Bromage and me. in short, some form of run-time compilation works
without actual compiling code. in particular, RegEx package compiles
regexps on the fly. my own program includes very simple variant of
run-time compiled regexps:

-- Compiled regexp                            Example
data RegExpr = RE_End                     --  ""
             | RE_Anything                --  "*"
             | RE_AnyStr  RegExpr         --  '*':"bc*"
             | RE_FromEnd RegExpr         --  '*':"bc"
             | RE_AnyChar RegExpr         --  '?':"bc"
             | RE_Char    Char RegExpr    --  'a':"bc"

-- |Compile string representation of regexpr into RegExpr
compile_RE s  =  case s of
  ""                         -> RE_End
  "*"                        -> RE_Anything
  '*':cs | cs `contains` '*' -> RE_AnyStr   (compile_RE  cs)
         | otherwise         -> RE_FromEnd  (compile_RE$ reverse s)
  '?':cs                     -> RE_AnyChar  (compile_RE  cs)
  c  :cs                     -> RE_Char   c (compile_RE  cs)

-- |Check match of string s with regexpr re
match_RE re s  =  case re of
  RE_End        -> null s
  RE_Anything   -> True
  RE_AnyStr   r -> any (match_RE r) (tails s)
  RE_FromEnd  r -> match_RE r (reverse s)
  RE_AnyChar  r -> case s of
                     ""   -> False
                     _:xs -> match_RE r xs
  RE_Char   c r -> case s of
                     ""   -> False
                     x:xs -> x==c && match_RE r xs

-- |Check match of string s with regexpr re, represented as string
match re {-s-}  =  match_RE (compile_RE re) {-s-}

actually, you will not find anything unusual here. the code for
matching with RegExpr is just constructed at runtime (as tree of
closures) which makes matching quite efficient

Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com

More information about the Haskell-Cafe mailing list