Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何使用HList调用多个参数的函数?_Scala_Shapeless - Fatal编程技术网

Scala 如何使用HList调用多个参数的函数?

Scala 如何使用HList调用多个参数的函数?,scala,shapeless,Scala,Shapeless,假设我有一个HList类型A::B::C::HNil和一个函数(A,B,C)=>D val hlist: A::B::C::HNil = ??? def foo(a: A, b: B, c: C): D = ??? 现在我需要一个函数a::B::C::HNil=>D,它使用foo返回D def bar(hslist: A::B::C::HNil): D = ??? 如何实现bar?您可以使用从HList到Tuple的无形状转换,并使用函数。Tuple与原始函数: def sum(a: Int

假设我有一个
HList
类型
A::B::C::HNil
和一个函数
(A,B,C)=>D

val hlist: A::B::C::HNil = ???
def foo(a: A, b: B, c: C): D = ???
现在我需要一个函数
a::B::C::HNil=>D
,它使用
foo
返回
D

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

如何实现
bar

您可以使用从
HList
Tuple
的无形状转换,并使用
函数。Tuple
与原始函数:

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

您可以使用Shapeless的
fntProduct
更直接地执行此操作,它提供了
toProduct
语法,用于将
函数n
转换为
函数1
,使用
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)
在许多情况下,您甚至可能不需要单独的
条定义