Explain Contramap

前端 未结 2 780
无人及你
无人及你 2021-01-30 21:16

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

// contravariant funct         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 21:44

    Suppose that you have a class Conversion[X, Y] representing a conversion from a value of type X to a value of type Y. You can either combine it with a function ? => X to preprocess the input or with a function Y=>? to postprocess the output. For instance:

    trait Conversion[X, Y] { self =>
    
      def apply(x: X): Y
    
      def map[Z](f: Y => Z) = new Conversion[X, Z] {
        def apply(x: X): Z = f(self.apply(x))
      }
    
      def contramap[W](f: W => X) = new Conversion[W, Y] {
        def apply(w: W): Y = self.apply(f(w))
      }
    
    }
    

提交回复
热议问题