Skip to content

Instantly share code, notes, and snippets.

@otf
Forked from bleis-tift/Program.fs
Created March 7, 2012 05:22
Show Gist options
  • Save otf/1991210 to your computer and use it in GitHub Desktop.
Save otf/1991210 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 CompilerError 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<CompilerError>
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