Skip to content

Instantly share code, notes, and snippets.

@nattybear
Last active October 28, 2022 03:59
Show Gist options
  • Save nattybear/66bc89ea5ccf5258fbb77db52a54a7db to your computer and use it in GitHub Desktop.
Save nattybear/66bc89ea5ccf5258fbb77db52a54a7db to your computer and use it in GitHub Desktop.
하스켈 Maybe 모노이드

이 글은 책 Haskell Programming from First Principles 일부를 읽고 정리한 것입니다.

타입 클래스 Num의 타입들이 SumProduct의 두가지 모노이드 연산이 있는 것처럼 타입 Maybe도 아래와 같이 여러가지 모노이드 연산이 있을 수 있다.

  • First
  • Last
  • Optional

이 글에서는 모노이드 연산인 mappend 혹은 <>를 편의상 합치다 라고 표현하기로 한다.

First

타입 Maybe끼리 합쳤을 때 왼쪽에 먼저 온 것이 결과가 된다.

ghci> First (Just 1) <> First (Just 2)
First (Just 1)

Last

타입 Maybe끼리 합쳤을 때 나중에 온 것이 결과가 된다.

ghci> Last (Just 1) <> Last (Just 2)
Last (Just 2)

Optional

타입 Optional끼리 합쳤을 때 Only 안에 있는 것끼리 합친 것이 결과가 된다.

data Optional a =
    Nada
  | Only a
  deriving (Eq, Show)
ghci> Only (Sum 1) `mappend` Only (Sum 2)
Only (Sum 3)

Nothing

위에서 언급한 세가지 유형 모두 mappend 연산의 인자 중 하나가 Nothing이라면 나머지 하나가 결과가 된다.

ghci> Nothing <> First 1
First 1
ghci> Last 1 <> Nothing
Last 1
ghci> Only (Sum 1) `mappend` Nada
Only (Sum 1)

두개 인자 모두 Nothing일 경우에는 당연히 결과도 Nothing이 된다.

ghci> Nothing <> Nothing
Nothing

대문 링크

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