01
시작하기
Hello World
printfn이 표준 출력 함수입니다.
fsharp
printfn "Hello, World!"let 바인딩
let은 불변이며, 변경 가능한 값에는 mutable + <-를 사용합니다.
fsharp
let x = 10
let mutable y = 20
y <- 25함수
함수는 기본적으로 커링(curried)됩니다.
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)
판별 유니언(DU)은 sum type이며, 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배열
배열은 가변(mutable)이며, .[]로 인덱싱합니다.
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?