11. F#ってこんな言語1 -- 冗語構文
// 行コメントが使える
let someFunction arg =
let x = f arg in // let式はinが必要
let y = g arg in
[ x; // リストの要素の区切りには;が必要
y ]
12. F#ってこんな言語1 -- 軽量構文
// 行コメントが使える(ので、//演算子は定義できない・・・)
let someFunction arg =
let x = f arg // 軽量構文ではinが不要
let y = g arg
[ x // 軽量構文では;を改行+インデントで代替可能
y ]
13. F#ってこんな言語1 -- matchのネスト
// OCamlerにはうれしい(?)match式のネスト
match f x with
| None -> None
| Some x ->
match g x with
| None -> None
| Some x -> h x
17. F#ってこんな言語2 -- アクティブパターン
// アクティブパターンの定義
let (|Even|Odd|) n =
if n % 2 = 0 then Even else Odd
// 定義したアクティブパターンに基づいた分岐
let f = function
| Even -> printfn "even"
| Odd -> printfn "odd"
21. F#ってこんな言語2 -- Maybeモナド
// ビルダーを定義して、
type MaybeBuilder () =
member __.Return(x) = Some x
member __.Bind(x, f) = Option.bind f x
let maybe = MaybeBuilder()
// 使う
let someFunc arg =
maybe {
let! x = f arg
let! y = g x
let! z = h y
return z
}
22. F#ってこんな言語2 -- 言語内DSLの例
// F#向けテスティングフレームワーク
let ``f should throw HogeException`` = test {
let! e = trap { it (f ()) }
do! e.GetType() === typeof<HogeException>
}
let ``g should return correct list`` =
let test (arg, expected) = test {
do! g arg === expected
}
parameterize {
source [
(0, [])
(1, [0])
(2, [0; 1])
]
do! test
}
25. F#ってこんな言語2 --- 消去型TPの例
type RecordRegex = Regex< @"(?<Name>^[^,]+),s*(?<Address>.+)" >
let res = RecordRegex().Match("山田太郎, どこか")
let name = res.Name.Value
let address = res.Address.Value
(* コンパイルすると、下記のコードと同じコードに展開される *)
// RecordRegexという型は消える
let res =
Regex(@"(?<Name>^[^,]+),s*(?<Address>.+)").Match("山田太郎, どこか")
// 型のプロパティとして見えていたものはただのインデクサを使ったアクセスへ
let name = res.Groups.["Name"].Value
let address = res.Groups.["Address"].Value
27. F#ってこんな言語2 -- 生成型TPの例
// 実際に型が作られる
type Edmx = EdmxFile<"Model.edmx">
let context = new Edmx.Model.Entities(conStr)
query { for user in context.Users do
where (user.Age >= 20)
select user }
|> Seq.iter (fun user -> printfn "%s" user.Name)
(* Model.edmxを読み込み、メタデータを取得し、
メタデータをもとにdbmlファイル(!)を生成し、
SqlMetal.exeにdbmlファイルを食わせることでC#ファイルを生成(!?)。
最終的に生成されたC#ファイルをコンパイル(!?!?)している。 *)
29. ・"An Atom Editor and Visual Studio Code package suite for
cross platform F# development."
・などなど
F#の開発環境
・Visual Studio
・Visual F# Tools(VS標準搭載)
・Visual F# Power Tools
・Ionide