F#은 함수형 우선(functional-first) .NET 언어로 OCaml에 영향을 받았다. 강력한 타입 시스템, 불변성, 패턴 매칭을 가지면서 C# 라이브러리와 완전한 상호운용성을 제공한다.
기본 문법
fsharp
// 불변 바인딩 (let)
let name = "홍길동"
let add x y = x + y
// 타입 추론 + 파이프라인 연산자
let result =
[1..10]
|> List.filter (fun x -> x % 2 = 0)
|> List.map (fun x -> x * x)
|> List.sum
// result = 220
// 판별 합집합 (Discriminated Union)
type Shape =
| Circle of radius: float
| Rectangle of width: float * height: float
let area = function
| Circle r -> System.Math.PI * r * r
| Rectangle(w,h) -> w * h
// 레코드 타입
type Person = {
Name: string
Age: int
}
let alice = { Name = "Alice"; Age = 30 }
let older = { alice with Age = 31 } // 불변 업데이트
비동기 프로그래밍
fsharp
open System.Net.Http
let fetchAsync (url: string) = async {
use client = new HttpClient()
let! response = client.GetStringAsync(url) |> Async.AwaitTask
return response.Length
}
// 병렬 비동기 실행
let urls = ["https://example.com"; "https://google.com"]
let lengths =
urls
|> List.map fetchAsync
|> Async.Parallel
|> Async.RunSynchronously
계산 표현식 (Computation Expression)
fsharp
// Result 모나드
type Result<'T, 'E> = Ok of 'T | Error of 'E
let result = result {
let! n1 = parseInt "42" // 실패 시 즉시 Error 반환
let! n2 = parseInt "10"
return n1 + n2
}
// 시퀀스 (지연 평가)
let fibs = seq {
let mutable a, b = 0, 1
while true do
yield a
let next = a + b
a <- b
b <- next
}
Seq.take 10 fibs |> Seq.toList
// [0; 1; 1; 2; 3; 5; 8; 13; 21; 34]
관련 문서