Map a homogenous HList of one type into a hetergenous HList of different types

送分小仙女□ 提交于 2019-12-05 18:28:00

You can do this pretty nicely with zipApply, which applies each element of an hlist of functions to the corresponding element in another hlist:

case class Title(title: String, words: List[String])
case class Author(firstName: String, lastName: String)

// For the sake of example:
def parseTitle(s: String): Title = Title(s, s.split(' ').toList)
def parseAuthor(s: String): Author =
  Author(s.takeWhile(_ != ' '), s.dropWhile(_ != ' ').tail)

import shapeless._

val funcs = parseTitle _ :: parseAuthor _ :: HNil
val strings = "The Lorax" :: "Dr. Suess" :: HNil

val book = funcs.zipApply(strings)

And then:

scala> println(book)
Title(The Lorax,List(The, Lorax)) :: Author(Dr.,Suess) :: HNil

If you need this to be more generic, you can use the ZipApply type class instead of simply calling zipApply on hlists with concrete types.

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