조건식: if...then...else

조건식: if...then...else

F#의 if...then...else는 단순히 코드를 조건에 따라 실행하는 문장이 아니라, 그 자체로 값을 만들어 내는 식(expression) 이에요. 어떤 분기를 실행하느냐에 따라 서로 다른 값을 돌려주죠. 이번 글에서는 이 조건식의 문법과 동작 방식, 실제 사용 예시를 살펴볼게요.

출처: https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/conditional-expressions-if-then-else

본문

if...then...else 식은 주어진 Boolean 식이 참인지 거짓인지에 따라 서로 다른 코드 분기를 실행하고, 그에 맞는 서로 다른 값을 평가해요.

문법 (Syntax)

if boolean-expression then expression1 [ else expression2 ]

설명 (Remarks)

위 문법에서 boolean-expressiontrue로 평가되면 expression1이 실행되고, 그렇지 않으면 expression2가 실행돼요.

다른 언어들과 마찬가지로 if...then...else 구성을 쓰면 코드를 조건에 따라 실행할 수 있어요. 다만 F#에서는 이 구문이 **식(expression)**이라서, 실제로 실행된 분기가 하나의 값을 만들어 냅니다. 이때 각 분기의 식 타입은 반드시 서로 일치해야 해요.

만약 명시적인 else 분기가 없다면 전체 타입은 unit이 되고, then 분기의 타입 역시 unit이어야 해요.

if...then...else 식을 연달아 이어 쓸 때는 else if 대신 elif 키워드를 쓸 수 있어요. 둘은 완전히 같은 의미예요.

예시 (Example)

다음 예시는 if...then...else 식을 어떻게 쓰는지 보여줘요.

let test x y =
  if x = y then "equals"
  elif x < y then "is less than"
  else "is greater than"

printfn "%d %s %d." 10 (test 10 20) 20

printfn "What is your name? "
let nameString = System.Console.ReadLine()

printfn "What is your age? "
let ageString = System.Console.ReadLine()
let age = System.Int32.Parse(ageString)

if age < 10 then
    printfn "You are only %d years old and already learning F#? Wow!" age

이 코드를 실행하면 다음과 같은 결과가 출력돼요.

10 is less than 20
What is your name? John
How old are you? 9
You are only 9 years old and already learning F#? Wow!

더 알아보기 (Learn more)