Deriving HList of zeroes from a type of HList of Monoids

帅比萌擦擦* 提交于 2019-12-04 13:44:49

It's fairly easy to define Monoid instance for every HList where each element type has its Monoid instance:

trait Monoid[T] {
  def zero: T
  def plus(t1: T, t2: T): T
}

object Monoid {
  implicit val HNilMonoid: Monoid[HNil] = new Monoid[HNil] {
    def zero = HNil
    def plus(hn1: HNil, hn2: HNil) = HNil
  }
  implicit def HConsMonoid[H, T <: HList](implicit hm: Monoid[H], tm: Monoid[T]): Monoid[H :: T] = 
    new Monoid[H :: T] {
      def zero = hm.zero :: tm.zero
      def plus(ht1: H :: T, ht2: H :: T) = 
        hm.plus(ht1.head, ht2.head) :: tm.plus(ht1.tail, ht2.tail)
    }
}

(actually, I would expect shapeless to be able to derive the above automatically, but I'm not an expert on shapeless)

Now, assuming that we have Monoid[Int] and Monoid[String] defined elsewhere, you can just:

implicitly[Monoid[Int :: String :: HNil]].zero

which is exactly what you want, i.e. a HList of zeros.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!