Skip to content

Instantly share code, notes, and snippets.

let inline readValue< ^T when ^T : (static member TryParse : string -> bool * ^T)> name =
let rec readValue() =
seq {
printf"input %s: " name
let str = Console.ReadLine ()
let success, value = (^T: (static member TryParse : string -> bool * ^T) str)
(* TryParse <- このTryParseを型パラメータの型のスタティックメソッドとして呼び出したい *)
if success
then yield value
@otf
otf / WpfTypeProvider.fs
Created December 3, 2011 20:44
WPF Type Provider
namespace WpfTypeProvider
open System
open System.Reflection
open Samples.FSharpPreviewRelease2011.ProvidedTypes
open Microsoft.FSharp.Core.CompilerServices
open Microsoft.FSharp.Quotations
open Xaml
open System.Linq.Expressions
[Test]
public void Maybe関数()
{
var safeParse = FuncUtil.Maybe<string, int>(int.Parse);
Assert.That(safeParse("123"), Is.EqualTo(new Option<int>(123)));
Assert.That(safeParse("ababa"), Is.EqualTo(Option<int>.None));
}
[Test]
public void Eitherに関数を適用_途中で失敗する関数()
{
var safeParse = FuncUtil.Either<string, int>(int.Parse);
var m = (Either<Exception, string>)Either.Right("hoge");
var result = from result1 in m
from result2 in safeParse(result1)
select result2;
Assert.That(result.Match(l => true, r => false), Is.True);
@otf
otf / Program.fs
Created March 7, 2012 05:22 — forked from bleis-tift/Program.fs
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 =
@otf
otf / Program.fs
Created April 28, 2012 12:54
coderetreat
open System
type World<'a> = 'a [,]
let tryGet ar x y =
try Some <| Array2D.get ar x y
with e -> None
let countAlive = List.collect Option.toList >> List.filter ((=) true) >> List.length
@otf
otf / gist:3106171
Created July 13, 2012 17:34
Formの解析
let (|FormParams|) (stream:Stream) =
readText stream |> HttpUtility.ParseQueryString |> nameValueCollections2List
@otf
otf / gist:3586997
Created September 1, 2012 20:55
ThreadLocalEvent
type ThreadLocalEvent<'T>() =
let handlers = new ThreadLocal<Handler<'T>>()
member this.Publish = this :> IDelegateEvent<Handler<'T>>
member this.Trigger(arg:'T) =
if handlers.Value <> null then
handlers.Value.Invoke(this, arg)
interface IDelegateEvent<Handler<'T>> with
type LogicalCallContextEvent<'T>() =
let id = Guid.NewGuid()
member this.Publish = this :> IDelegateEvent<Handler<'T>>
member this.Trigger(arg:'T) =
if CallContext.LogicalGetData(id.ToString()) <> null then
(CallContext.LogicalGetData(id.ToString()) :?> Handler<'T>).Invoke(this, arg)
interface IDelegateEvent<Handler<'T>> with
let rec move (x, y) r g n =
if x < 0 || y < 0 || x > g || y > g then n
elif (x,y) = (g, g) then n + 1
else match List.tryFind ((=) (x, y)) r with
| Some _ -> n
| None ->
[(x + 1, y); (x, y + 1); (x - 1, y); (x, y - 1)]
|> List.map (fun xy -> move xy ((x, y)::r) g)
|> List.fold (|>) n