Question

So the problem is in understandig HLists of shapeless library https://github.com/milessabin/shapeless ; I'm using HLists to store some functions i.e. :

val list = HList(
    function1(_),
    function2(_),
    ....
    functionn(_)
);

And it works perfect: I can take any function from list and apply it: list.head(object)

But, i have problem applying it with map function (list map mapFunc):

object mapFunc extends Poly1 {
  implicit def default[T] =
    at[T](t => {
      t(obj)
    })
}

It says Application doesnt take parameters. So how can i deal with it? Mb I dont understand smth? I'm new to Scala.

p.s. there is an interesting effect with constructor this code is building lil bit incorrect:

function1(_) :: function2(_) :: HNil it is recognized as function of some type, but HList(function1(_), function2(_)) has the right type.

EDIT

'p.s.' was decided - function1(_) :: function2(_) :: HNil really has type mismatch; but function1 _ :: function2 _ :: HNil is ok!

Was it helpful?

Solution

First for your last question—you need to conclude the list with HNil, not HList. So if for example we have the following:

def function1(s: String) = "foo " + s
def function2(s: String) = s.toInt
def function3(s: String) = s + " bar"

We'd write:

val list = function1 _ :: function2 _ :: function3 _ :: HNil

Since :: is like the cons operator that you'll find in the Scala standard library (and other languages) in that it takes its first argument (an item) and prepends it to its second (a list).

Now for your first question. Given the HList I just defined, we could write the following:

val obj = "13"

object mapFunc extends Poly1 {
  implicit def funcTo[T] = at[String => T](f => f(obj))
}

And then:

scala> (list map mapFunc) == "foo 13" :: 13 :: "13 bar" :: HNil
res0: Boolean = true

The key is that you need to represent the fact that the case applies when the map element is a function from a string (or whatever your object type is) to something.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top