Gleam은 Erlang VM(BEAM) 위에서 동작하는 정적 타입 함수형 언어다. Erlang의 동시성·내결함성과 Rust에서 영감받은 타입 시스템을 결합했다. JavaScript로도 컴파일된다.
기본 문법
gleam
import gleam/io
import gleam/list
import gleam/result
// 함수 정의
pub fn greet(name: String) -> String {
"Hello, " <> name <> "!"
}
// 커스텀 타입 (Algebraic Data Type)
pub type Shape {
Circle(radius: Float)
Rectangle(width: Float, height: Float)
}
pub fn area(shape: Shape) -> Float {
case shape {
Circle(r) -> 3.14159 *. r *. r
Rectangle(w, h) -> w *. h
}
}
// 파이프라인 연산자
pub fn process(numbers: List(Int)) -> Int {
numbers
|> list.filter(fn(n) { n > 0 })
|> list.map(fn(n) { n * n })
|> list.fold(0, fn(acc, n) { acc + n })
}
Result 타입과 오류 처리
gleam
import gleam/int
import gleam/result
pub fn safe_divide(a: Int, b: Int) -> Result(Int, String) {
case b {
0 -> Error("Division by zero")
_ -> Ok(a / b)
}
}
// use 구문: 모나딕 체이닝
pub fn compute(a: String, b: String) -> Result(Int, String) {
use n1 <- result.try(int.parse(a))
use n2 <- result.try(int.parse(b))
safe_divide(n1, n2)
}
BEAM VM의 장점 활용
gleam
import gleam/otp/actor
import gleam/erlang/process
// Actor 모델 (Erlang 기반)
pub fn start_counter() {
let assert Ok(subject) = actor.start(0, fn(msg, state) {
case msg {
Increment -> actor.continue(state + 1)
Get(reply) -> {
process.send(reply, state)
actor.continue(state)
}
}
})
subject
}
관련 문서