lambda中的懒惰参数

时间:2017-08-28 16:20:06

标签: scala lambda types anonymous-function

是否可以在以下代码段中内联my函数?

import scala.annotation.tailrec


object Ex14AppendViaFold extends App {
  val l = List[Int](1, 2, 3, 4)
  val l2 = List[Int](9, 8, 7, 6)

  def append[A](l1: => List[A], l2: => List[A]) = {
    def my(acc: => List[A], e: => A) = Cons(e, acc): List[A]

    List.foldLeft(List.reverse(l1), l2)(my)
  }

  println(append(l, l2))
}

sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]


object List{
  def apply[A](as: A*): List[A] = // Variadic function syntax
    if (as.isEmpty) Nil
    else Cons(as.head, apply(as.tail: _*))

  def reverse[A](l :List[A]) =
    List.foldLeft[A, List[A]](l,Nil)((acc, elem) => Cons(elem,acc))

  @tailrec
  def foldLeft[A,B](l: List[A], z: B)(f: ( => B, => A) => B): B = l match {
      case Cons(h, tail) => foldLeft(tail, f(z, h))(f)
      case Nil => z
  }
} 

1 个答案:

答案 0 :(得分:1)

基于this回答:

  List.foldLeft(List.reverse(l1), l2)(
    ((acc, e) => Cons(e, acc)): ((=> List[A], => A) => List[A])
  )

所以你可以指定lambda的类型。