01
はじめに
Hello World
printfn が標準の出力関数です。
fsharp
printfn "Hello, World!"let バインディング
let は不変(イミュータブル)で、変更可能な値には mutable と <- を使います。
fsharp
let x = 10
let mutable y = 20
y <- 25関数
関数はデフォルトでカリー化されます。
fsharp
let add a b = a + b
let result = add 3 4
// Explicit types
let divide (a: float) (b: float) : float = a / bパイプ演算子
|> は左から右へ値を渡す演算子で、F# で非常によく使われます。
fsharp
[1; 2; 3; 4; 5]
|> List.filter (fun x -> x % 2 = 0)
|> List.map (fun x -> x * 2)
|> List.sum02
型
レコード
レコードは 'with' で不変のまま更新できます。
fsharp
type Person = { Name: string; Age: int }
let p = { Name = "Alice"; Age = 30 }
let p2 = { p with Age = 31 }判別共用体
判別共用体(DU)は直和型で、match で網羅的に処理できます。
fsharp
type Shape =
| Circle of radius: float
| Rectangle of w: float * h: float
let area s =
match s with
| Circle r -> 3.14 * r * r
| Rectangle (w, h) -> w * hOption
Option<T> = Some T | None で null を安全に扱います。
fsharp
let safeDiv a b =
if b = 0 then None else Some (a / b)
match safeDiv 10 2 with
| Some v -> printfn "%d" v
| None -> printfn "error"03
コレクション
リスト
List モジュールに標準的な関数型の操作が揃っています。
fsharp
let xs = [1; 2; 3; 4; 5]
List.map (fun x -> x * 2) xs
List.filter (fun x -> x > 2) xs
List.fold (+) 0 xs配列
配列は可変で、.[] でインデックスアクセスします。
fsharp
let arr = [|1; 2; 3|]
arr.[0] <- 10シーケンス
seq は遅延評価で、IEnumerable に相当します。
fsharp
seq { 1..10 }
seq { for i in 1..10 do if i % 2 = 0 then yield i }Was this helpful?