Stefan K.
Stefan K.

Reputation: 7851

Lazy arguments in lambda

Is it possible to inline the my function in the following snippet?

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
  }
} 

Upvotes: 1

Views: 333

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51683

Based on this answer:

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

So you can specify the type of lambda.

Upvotes: 2

Related Questions