Let $C$ be a constructor which takes a variable as parameter.

$C$ is a Functor if $C$ has the following ability.

For example, we can write such a function map for Optional. (Well, swift already has such built-in function.)

123456789101112131415161718192021222324

extensionOptional{funcmap<U>(f:Wrapped->U)->U?{switchself{case.Some(letx):returnf(x)case.None:return.None}}// take out the wrapped itemfunctoValue()->Wrapped?{switchself{case.Some(letx):returnxcase.None:return.None}}}// A -> BfuncplusTwo(addend:Int)->Double{returnDouble(addend)+2.0}// C[A] -> C[B]Int?.Some(3).map(plusTwo)// Change Optional<Int>(3) into Optional<Double>(5.0)

// This is a custom operatorinfixoperator<^>{associativityleft}func<^><T,U>(a:T?,f:T->U)->U?{returna.map(f)}Optional.Some(2)<^>plusThree// Int?(5)Optional.Some(2)<^>plusThree<^>plusThree// Int?(8)

$C$ is a Applicative if $C$ has the following ability.

1234567891011121314151617181920212223242526272829

extensionOptional{// Note that function `f` is ALSO wrapped in Optional typefuncapply<U>(f:(Wrapped->U)?)->U?{switchf{case.Some(letsomeF):returnself.map(someF)case.None:return.None}}}extensionArray{// Note that function `f` is ALSO wrapped in Array typefuncapply<U>(fs:[Element->U])->[U]{varresult=[U]()forfinfs{forelementinself.map(f){result.append(element)}}returnresult}}// This is a IntFunction? typeletplusThreeBox=Optional<IntFunction>.Some(plusThree)Int?.Some(3).apply(plusThreeBox)// Int?(6)[1,2,3].apply([{$0+10},{$0+100}])// [11, 12, 13, 101, 102, 103]