Haskell 타입 클래스(Type Classes)는 다형성 함수를 타입 안전하게 정의하는 메커니즘이다. Scala, Rust, Swift 등 현대 언어에 큰 영향을 미쳤다.
타입 클래스 정의
haskell
-- 타입 클래스 정의
class Describable a where
describe :: a -> String
shortDesc :: a -> String -- 기본 구현
shortDesc = take 20 . describe
-- 인스턴스
data Color = Red | Green | Blue
instance Describable Color where
describe Red = "빨간색"
describe Green = "초록색"
describe Blue = "파란색"
-- 사용
main = mapM_ (putStrLn . describe) [Red, Green, Blue]
주요 내장 타입 클래스
haskell
-- Eq: 동등성
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
x /= y = not (x == y) -- 기본 구현
-- Ord: 순서 (Eq의 서브클래스)
class Eq a => Ord a where
compare :: a -> a -> Ordering -- LT | EQ | GT
-- Functor: 맵핑
class Functor f where
fmap :: (a -> b) -> f a -> f b
-- Monad
class Applicative m => Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
newtype 파생
haskell
newtype Name = Name String
deriving (Eq, Ord, Show) -- 자동 인스턴스 생성
newtype Age = Age Int
deriving (Eq, Ord, Show, Num)
-- GHC GeneralizedNewtypeDeriving으로 내부 타입 인스턴스 재사용
함수자 / 애플리커티브 / 모나드
haskell
-- Functor: f a → f b
fmap (+1) (Just 5) -- Just 6
fmap (+1) [1,2,3] -- [2,3,4]
-- Applicative: f (a→b) → f a → f b
Just (+3) <*> Just 5 -- Just 8
[(+1),(+2)] <*> [10] -- [11,12]
-- Monad: 체이닝
Just 5 >>= \x -> Just (x * 2) -- Just 10
[1,2,3] >>= \x -> [x, x*10] -- [1,10,2,20,3,30]
관련 개념