Skip to content

Instantly share code, notes, and snippets.

@nattybear
Last active December 30, 2020 11:30
Show Gist options
  • Save nattybear/c6ad0618869bd7521d719f270436bff1 to your computer and use it in GitHub Desktop.
Save nattybear/c6ad0618869bd7521d719f270436bff1 to your computer and use it in GitHub Desktop.
하스켈 if

클까 작을까

아래 함수 bigOrSmallint를 넣으면 string이 나온다.

// cpp
string bigOrSmall(int x)
{
  if (x < 10)
    return "small";
  else
    return "big";
}

하스켈로는 아래처럼 쓸 수 있다. 먼저 타입만 적어보자. Int를 넣으면 String이 나오는 함수이다.

bigOrSmall :: Int -> String

너무 이쁘다

함수 내용까지 같이 적어보자.

bigOrSmall :: Int -> String
bigOrSmall x = if x < 0
                 then "small"
                 else "big"

다른 언어와 별로 다를 게 없어 보인다. then이 생소한 정도이다.

그런데 만약에 if만 적고 else를 적지 않으면 어떻게 될까?

else를 꼭 적어야 해

C++에서는 컴파일 하는데 아무 문제가 없다.

string bigOrSmall(int x)
{
  if (x < 10)
    return "small"
}

물론 이렇게 하면 컴파일은 잘 되지만 실행시켰을 때 x10보다 작지 않은 경우 에러가 난다.

string bigOrSmall(int x)
{
  if (x < 10)
    return "small";
}

int main()
{
  bigOrSmall(9);  // "small"
  bigOrSmall(10);  // error!
  return 0;
}

하스켈에서는 if를 사용할 때 else를 반드시 적어야 한다. 그렇지 않으면 컴파일 에러가 난다.

-- 컴파일 에러가 나는 코드
bigOrSmall :: Int -> String
bigOrSmall x = if x < 10
                 then "small"

이렇게 else를 강제함으로써 프로그래머의 실수를 미연에 방지해준다. 고마워요 하스켈

진짜 쉬운 하스켈

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment