Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

scala - Explain Contramap

Can someone explain contramap to me? What would this implementation look like? What would good examples of usage look like?

// contravariant functor
trait Contravariant[F[_]] {
  def contramap[A, B](f: B => A): F[A] => F[B]
}

Source: http://tmorris.net/posts/functors-and-things-using-scala/index.html

question from:https://stackoverflow.com/questions/15457015/explain-contramap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you look at the following Ordering.on method of the standard library:

def on[U](f: U => T): Ordering[U]

You'll see that on transforms an Ordering[T] into an Ordering[U] while taking a function from U to T. So the method on witnesses the fact that Ordering can be seen as a Contravariant functor with:

def contramap[A, B](f: B => A) = (fa: Ordering[A]) => fa.on(f)

I also saw the blog post from Tony and it helped me finally makes sense of this three year old answer from retronym to one of my question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...