
프로그래밍 언어론
Functor (Programming)함자
함자(Functor)는 구조를 보존하면서 내부 값에 함수를 적용할 수 있는 타입 클래스다. 범주 이론의 함자 개념을 프로그래밍으로 가져온 것이다.
Functor 타입 클래스
haskell
class Functor f where
fmap :: (a -> b) -> f a -> f b
-- 함자 법칙:
-- 항등: fmap id = id
-- 합성: fmap (g . f) = fmap g . fmap f주요 함자 구현
haskell
-- Maybe 함자
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just x) = Just (f x)
-- List 함자
instance Functor [] where
fmap = map
-- Either 함자 (오른쪽 값에만 적용)
instance Functor (Either e) where
fmap _ (Left e) = Left e
fmap f (Right x) = Right (f x)
-- IO 함자
instance Functor IO where
fmap f io = io >>= (return . f)
-- Tree 함자
data Tree a = Leaf | Node (Tree a) a (Tree a)
instance Functor Tree where
fmap _ Leaf = Leaf
fmap f (Node l x r) = Node (fmap f l) (f x) (fmap f r)공변 함자 vs 반변 함자
haskell
-- 공변 함자 (Covariant): 일반 Functor
-- f a -> (a -> b) -> f b (a가 결과 위치)
-- 반변 함자 (Contravariant)
-- f a -> (b -> a) -> f b (a가 입력 위치)
class Contravariant f where
contramap :: (b -> a) -> f a -> f b
-- 예: Predicate (a -> Bool)
newtype Predicate a = Predicate { runPredicate :: a -> Bool }
instance Contravariant Predicate where
contramap f (Predicate p) = Predicate (p . f)
-- 양변 함자 (Profunctor): 입력은 반변, 출력은 공변
class Profunctor p where
dimap :: (a' -> a) -> (b -> b') -> p a b -> p a' b'JavaScript에서의 함자
javascript
// Array는 함자
[1, 2, 3].map(x => x * 2) // [2, 4, 6]
// Maybe 함자 구현
class Maybe {
constructor(value) { this.value = value; }
static of(value) { return new Maybe(value); }
map(fn) {
return this.value == null
? Maybe.of(null)
: Maybe.of(fn(this.value));
}
}
Maybe.of(5).map(x => x * 2).map(x => x + 1); // Maybe(11)
Maybe.of(null).map(x => x * 2); // Maybe(null)