F# 4.6의 새로운 기능
F# 4.6의 새로운 기능 (What's new in F# 4.6)
F# 4.6은 F# 언어에 여러 가지 개선점을 더해 준 버전이에요. 이번 업데이트에서 특히 눈에 띄는 두 가지, 무명 레코드(Anonymous records)와 ValueOption 함수를 중심으로 함께 살펴볼게요.
출처: What's new in F# 4.6 - Microsoft Learn
본문
시작하기 (Get started)
F# 4.6은 모든 .NET Core 배포판과 Visual Studio 도구에서 사용할 수 있어요. F#을 처음 시작한다면 Get started with F# 문서를 참고해 보세요.
무명 레코드 (Anonymous records)
무명 레코드는 F# 4.6에서 처음 도입된 새로운 F# 형식이에요. 이름이 붙은 값들을 단순하게 묶어 주는데, 사용하기 전에 따로 선언할 필요가 없답니다. 구조체(struct)나 참조 형식(reference type)으로 선언할 수 있고, 기본값은 참조 형식이에요.
open System
let getCircleStats radius =
let d = radius * 2.0
let a = Math.PI * (radius ** 2.0)
let c = 2.0 * Math.PI * radius
{| Diameter = d; Area = a; Circumference = c |}
let r = 2.0
let stats = getCircleStats r
printfn "Circle with radius: %f has diameter %f, area %f, and circumference %f"
r stats.Diameter stats.Area stats.Circumference
값 형식(value type)들을 한데 묶고 성능에 민감한 시나리오에서 쓰고 싶다면, 구조체로도 선언할 수 있어요.
open System
let getCircleStats radius =
let d = radius * 2.0
let a = Math.PI * (radius ** 2.0)
let c = 2.0 * Math.PI * radius
struct {| Diameter = d; Area = a; Circumference = c |}
let r = 2.0
let stats = getCircleStats r
printfn "Circle with radius: %f has diameter %f, area %f, and circumference %f"
r stats.Diameter stats.Area stats.Circumference
무명 레코드는 굉장히 강력해서 다양한 상황에서 활용할 수 있어요. 자세한 내용은 Anonymous records 문서를 확인해 보세요.
ValueOption 함수
F# 4.5에서 추가된 ValueOption 형식은 이제 Option 형식과 "모듈 바인딩 함수" 패리티(module-bound function parity)를 갖추게 됐어요. 자주 쓰이는 예시를 몇 가지 볼게요.
// Multiply a value option by 2 if it has value
let xOpt = ValueSome 99
let result = xOpt |> ValueOption.map (fun v -> v * 2)
// Reverse a string if it exists
let strOpt = ValueSome "Mirror image"
let reverse (str: string) =
match str with
| null
| "" -> ValueNone
| s ->
str.ToCharArray()
|> Array.rev
|> string
|> ValueSome
let reversedString = strOpt |> ValueOption.bind reverse
이렇게 해서 값 형식으로 성능을 높이고 싶은 시나리오에서도 ValueOption을 Option처럼 그대로 사용할 수 있게 됐어요.
더 알아보기
- Anonymous records — 무명 레코드의 문법과 활용 방법
- Get started with F# — F# 입문 가이드