Skip to content

Instantly share code, notes, and snippets.

@bleis-tift
Created May 3, 2011 03:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bleis-tift/952764 to your computer and use it in GitHub Desktop.
Save bleis-tift/952764 to your computer and use it in GitHub Desktop.
F#で文字列をeval
open Microsoft.FSharp.Compiler.CodeDom
open System.Reflection
open System.CodeDom.Compiler
type EvalResult<'a> =
| CompileError of string seq
| RuntimeError of exn
| Success of 'a
let eval args expr =
use provider = new FSharpCodeProvider()
let src = "module Temp\n\
let body args =\n " + expr
let param = CompilerParameters(GenerateInMemory=true)
let res = provider.CompileAssemblyFromSource(param, src)
let errors = res.Errors |> Seq.cast<string>
if not(Seq.isEmpty errors) then
CompileError errors
else
let asm = res.CompiledAssembly
let t = asm.GetType("Temp")
let m = t.GetMethod("body")
try
Success(m.Invoke(null, args |> List.toArray) :?> 'a)
with
e -> RuntimeError e
[<EntryPoint>]
let main _ =
match @"failwithf ""%s world!"" args" |> eval [ "hoge" ] with
| Success _ -> printfn "success!"
| _ -> printfn "oops..."
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment