Scala shapeless function corresponding to the vanilla "zipped" on regular lists?

StackOverflow https://stackoverflow.com/questions/19572579

  •  01-07-2022
  •  | 
  •  

문제

This is a newb question.

I'd like to do something like this:

val a = 1 :: "hi" :: HNil
val b = "foo" :: 2.2 :: HNil
val c = 3 :: 4 :: HNil

val d = (a, b, c).zip // Like "zipped" on tuples of regular lists.

In the above, d should have the value:

(1, "foo", 3) :: ("hi", 2.2, 4) :: HNil

Is there a clean way to do this?

도움이 되었습니까?

해결책

You'll need to convert the tuple to an HList first. In 1.2.x:

import shapeless._, Tuples._

val a = 1 :: "hi" :: HNil
val b = "foo" :: 2.2 :: HNil
val c = 3 :: 4 :: HNil

(a, b, c).hlisted.zipped

In 2.0.0 you have more options:

import shapeless._, syntax.std.tuple._

val a = 1 :: "hi" :: HNil
val b = "foo" :: 2.2 :: HNil
val c = 3 :: 4 :: HNil

(a, b, c).productElements.zip

Or:

import shapeless._, syntax.std.tuple._

val a = (1, "hi")
val b = ("foo", 2.2)
val c = (3, 4)

(a, b, c).zip

This last will return a tuple of 3-tuples, which may or may not work for you.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top