Skip to content

Instantly share code, notes, and snippets.

@nattybear
Last active June 22, 2021 22:59
Show Gist options
  • Save nattybear/417d862ca39c964cea3a28bed2b72ce0 to your computer and use it in GitHub Desktop.
Save nattybear/417d862ca39c964cea3a28bed2b72ce0 to your computer and use it in GitHub Desktop.
하스켈 타입 클래스

타입 클래스

Eq는 타입 클래스이다.

class Eq a where
  (==) :: a -> a -> Bool

Eq 인스턴스가 구현되어 있는 데이터 타입이라면 함수 ==를 쓸 수 있다.

instance Eq Bool where
  True  == True  = True
  False == False = True
  _     == _     = False

타입 BoolEq 인스턴스가 있기 때문에 ==를 쓸 수 있다.

ghci> True == True
True
ghci> True == False
False

Functor

Functor는 타입 클래스이다.

class Functor f where
  fmap :: (a -> b) -> f a -> f b

Functor 인스턴스가 있는 타입이라면 함수 fmap을 쓸 수 있다.

instance Functor Maybe where
  fmap _ Nothing  = Nothing
  fmap f (Just x) = Just (f x)

타입 MaybeFunctor 인스턴스가 있어서 fmap을 쓸 수 있다.

ghci> fmap (+1) (Just 2)
Just 3
ghci> fmap (+1) Nothing
Nothing

부를 때

사람들은 보통

MaybeFunctor

라고 말한다. 이 말은 사실

타입 Maybe는 타입 클래스 Functor의 인스턴스가 구현되어 있어

라는 말과 같다.

그러니까 사람들이

A는 모나드야

라고 말한다면 그건

타입 A는 타입 클래스 Monad의 인스턴스가 구현되어 있어

라는 뜻이다.

그렇다. 모나드는 부리또가 아니라 그냥 타입 클래스일 뿐이다.

대문 링크

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