How to call a function of multiple arguments using HList?

Suppose I have HListtype A::B::C::HNiland function(A, B, C) => D

val hlist: A::B::C::HNil = ???
def foo(a: A, b: B, c: C): D = ???

Now I need a funciton A::B::C::HNil => Dthat uses footo return D.

def bar(hslist: A::B::C::HNil): D = ???

How would you implement it bar?

+4
source share
2 answers

You can do this in a bit more detail using Shapeless FnToProduct, which provides syntax toProductfor converting FunctionNto Function1using HList:

import shapeless._, syntax.std.function._

type A = String
type B = Symbol
type C = Int
type D = List[String]

val hlist: A :: B :: C :: HNil = "foo" :: 'x :: 1 :: HNil

def foo(a: A, b: B, c: C): D = List.fill(c)(a + b)

def bar(hslist: A :: B :: C :: HNil): D = (foo _).toProduct.apply(hslist)

In many cases, you probably won't even need a separate definition bar.

+9
source

HList Tuple Function.tupled :

def sum(a: Int, b: Int) = a + b

def sumHList(hlist: Int :: Int :: HNil) = {
  val tupledSum = Function.tupled(sum _)
  tupledSum(hlist.tupled)
}

def sumHList2(hlist: Int :: Int :: HNil) = hlist.head + hlist.tail.head

sum(1, 2)
sumHList(1 :: 2 :: HNil)
sumHList2(1 :: 2 :: HNil)
// result from all three = 3
+2

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


All Articles