Converters in Swift

I studied functional programming in Swift through Haskell and came across this interesting Transducers concept. One example code has implemented a mapping function that basically spits out a converter, given that we pass the transformation rule as a parameter.

Inspired, I quickly translated this into the Swift equivalent, and this is what I got:

 func mapping < A, B, C> (f: A -> B) -> ( ( (C,B) -> C) -> ( (C,A) -> C) ) { return { r in return { result, a in return r(result,f(a)) } } } 

Now my question is: notice how the conversion function goes from A to B ( (A -> B) ), but the converter goes from B to A ( ( (C,B) -> C) -> ( (C,A) -> C) )? Why is this? I am sure that this is not accidental, because this order matters. Haskell experts, anyone?

+5
source share
2 answers

See where f is called. It converts A to B , and the result is used as an argument to r . Therefore, r must expect a B ; we use the function A -> B to pre-process the input of the function (C, B) -> C , which leads to the function (C, A) -> C

In general, this reversal occurs whenever we transform the system to change its β€œinput”. If we transform the system to change its "exit", there is no appeal 1 .

 X -> A ---> A -> B ---> B -> Y 

If I have a function A -> B , and I want to make something out of it that emits Y , I need to display the output function B -> Y above it. This is called covariance because the thing I want to change ( B in A -> B ) "varies depending on the" function I that maps it ( B -> Y ). It is said that B is in a positive position in A -> B

If I have a function A -> B , and I want to make something out of it that accepts instead of X , I need to display the function X -> A by entering it. This is called contravariance because the thing I want to change ( A in A -> B ) β€œchanges depending on theβ€œ function I displayed above it ”( X -> A ). It is said that A is in a negative position in A -> B


1 Higher-order programming means that we can transform the system to change the input signal in the output of something that contributes to the outpu of "our system ...! The terms" negative position "and" positive position "suggest that negative is negative the result is positive, etc.

+4
source

The order is inverted because your mapping acts on the argument. You use the function A -> B so that the pair (C,A) matches the type of function (C,B) -> C So, in the end, you get a function (C,A) -> C , which converts A into a pair in B as a preliminary step.

In a more general case, mapping is an example of a contravariant functor, in contrast to covariant functors (for example, the Haskell Functor class), in which the order is not inverted. To illustrate, here is the corresponding Haskell package .

+1
source

All Articles