Display by Archived HLists

I am trying to use a shapeless selection of a non-empty value from two HLists:

import shapeless.{ HNil, Poly2}

object choose extends Poly2 {
  implicit def caseInt =
    at[Int,Int]{
      case (_,n) if n > 0 => n
      case (o,_) => o
    }

  implicit def caseString  =
    at[String,String] {
      case (_,n) if n.nonEmpty => n
      case(o,_) => o
    }
}


val g = "a" :: "" :: 0 :: HNil
val h = "" :: "a"  :: 5 :: HNil

g.zip(h).map(choose)

I get an error message when implicitly matching. If I understand correctly, I need to provide proof that the zip result is displayable, but I'm not sure how to do this

+4
source share
1 answer

You are very close, but the definition is a chooselittle wrong: mapaccepts Poly1not a Poly2.

You map the hlist of tuples, so you need a polymorphic function that takes one argument (tuple). Instead, you provide a polymorphic function with two arguments. The difference is subtle, but it is.

, :

import shapeless.{ HNil, Poly1 }

object choose extends Poly1 {
  implicit def caseInt =
    at[(Int,Int)]{
      case (_,n) if n > 0 => n
      case (o,_) => o
    }

  implicit def caseString  =
    at[(String,String)] {
      case (_,n) if n.nonEmpty => n
      case(o,_) => o
    }
}

val g = "a" :: "" :: 0 :: HNil
val h = "" :: "a"  :: 5 :: HNil

g.zip(h).map(choose) // "a" :: "a" :: 5 :: HNil

, Poly1 Poly2 at .

+4

Source: https://habr.com/ru/post/1653621/


All Articles