3 ms·
I'll be using pseudo code and skip over some technical details that are entirely irrelevant to this conversation in my answer. I hope I understood your question
by nrinaudo 12y ago
I'll be using pseudo code and skip over some technical details that are entirely irrelevant to this conversation in my answer. I hope I understood your question correctly and not answering something else entirely.
First, a functor doesn't go from A to F[B] but from F[A] to F[B]. A to F[B] looks suspiciously like something a monad does, a topic we don't want to get into.
Your example is a functor that maps unary functions to unary functions by composing them. It's a good if slightly complicated example: unary functions have two type parameters (A and B in A => B), while the slide's Functor only takes one. That is, you want to write a Functor[A => B], but you cannot, or at least not directly.
What you do is fix one of the parameters. You don't write a Functor for all unary functions, but a Functor for all unary functions whose parameter type is C (for concrete): Functor[C => A], where C is a concrete type and A the functor's type parameter.
This functor's map method takes an instance of (C => A), a function f: A => B, and yields a function C => B. The only non-pathological implementation of this is composition: C => A => B
What I just wrote makes it sound like you need to write a Functor implementation for all possible parameter types, but that luckily isn't true: writing a function that yields a Functor[C => A] for any given type parameter C is trivial. I'll put the code here just to show it is, but you don't really need to understand it:
// I know the C => ? isn't standard Scala, I'm using kind-projector syntax to make this readable.
implicit def functionFunctor[C] = new Functor[C => ?] {
override def map[A, B](fa: C => A)(f: A => B): C => B = f compose fa
}
To go back to your concrete example: you just need to get functionFunctor[X] and call map on (x => x * 0.5) to get your function from X to double. Note that some technical details are skipped (partial application, calling the binary function map with a single parameter), but I arbitrarily deem them irrelevant to my point.
- im3w1l 12y agoYou misunderstand my question. I realize in hindsight how it was ambiguous. I used the word "object" like it is used in slide 55. Functors map objects to objects and arrows to arrows. I.e. arrow is the (co)domain of the functor, and object is the (co)domain of the (co)domain of the functor.