Skip to content

Instantly share code, notes, and snippets.

@wotjd
Created July 23, 2019 07:04
Show Gist options
  • Save wotjd/48d9dc3d8d801019c66491e8d3a033ef to your computer and use it in GitHub Desktop.
Save wotjd/48d9dc3d8d801019c66491e8d3a033ef to your computer and use it in GitHub Desktop.
// https://ko.wikipedia.org/wiki/함자_(수학)
struct F<X> {
let x : X?
init(_ x: X?) { self.x = x }
func map<Y>(_ f : @escaping (X) -> Y?) -> F<Y> {
guard let x = self.x else {
return F<Y>(nil)
}
return F<Y>(f(x))
}
}
// C와 D가 범주라 하자. 이때 C와 D 사이의 함자 F: C -> D는 다음과 같은 데이터로 구성된다.
// C의 임의의 대상 X에 대해 대응되는 D의 대상 F(X)
// => F: X -> F(X), 임의의 값 X 로 init 이 가능해야 하며, 리턴값은 랩핑되어 있음
// C의 임의의 사상 f: X -> Y 에 대해 대응되는 D의 사상 F(f): F(X) -> F(Y)
// => X 를 Int, Y 를 Double 으로 가정하면
typealias X = Int
typealias Y = Double
func f(_ x: X) -> Y {
return Y(x) // Double(Int)
}
let x = X()
print("F(f): F(X) -> F(Y) = \(F(x).map(f))") // F(f): F(X) -> F(Y) = F<Double>(x: Optional(0.0))
// 이 데이터는 다음 두 조건을 만족시켜야 한다.
// (항등사상의 보존) F(id(x)) = id(F(X))
func id<X>(_ x: X) -> X {
return x
}
print("항등사상의 보존, F(id(X)) = id(F(X))")
print("F(id(X)) = \(F(id(x)))") // F(id(X)) = F<Int>(x: Optional(0))
print("id(F(X)) = \(id(F(x)))") // id(F(X)) = F<Int>(x: Optional(0))
print("사상 합성의 보존, C의 임의의 사상 f: X -> Y 와 g: Y -> Z 에 대해 F(g o f) = F(g) o F(f)")
typealias Z = String
func g(_ y: Y) -> Z {
return Z(y)
}
print(F(g(f(x)))) // F<String>(x: Optional("0.0"))
print(F(f(x)).map(g)) // F<String>(x: Optional("0.0"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment