Created
May 3, 2011 03:19
-
-
Save bleis-tift/952764 to your computer and use it in GitHub Desktop.
F#で文字列をeval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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