Вопрос

I'd love to have let construct similar to the one in Haskell in Scala. I tried a few ways, but none seems to be good. Here's some code:

object CustomLet extends App {
  val data = for (i <- 1 to 1024; j <- 1 to 512) yield (i % j) * i * (i + 1) - 1

  def heavyCalc() = { println("heavyCalc called"); data.sum }

  def doSomethingWithRes(res: Int) = {
    println(s"${res * res}")
    1
  }

  def cond(value: Int): Boolean = value > 256

  // not really usable, even though it's an expression (2x heavyCalc calls)
  def withoutLet() = if (cond(heavyCalc())) doSomethingWithRes(heavyCalc()) else 0

  // not an expression
  def letWithVal(): Int = {
    val res = heavyCalc()
    if (cond(res)) doSomethingWithRes(res)
    else 0
  }

  // a lot of code to simulate "let", at least it is an expression
  def letWithMatch(): Int = heavyCalc() match {
    case res => if (cond(res)) doSomethingWithRes(res) else 0
  }

  // not perfect solution from
  // http://stackoverflow.com/questions/3241101/with-statement-equivalent-for-scala/3241249#3241249
  def let[A, B](param: A)(body: A => B): B = body(param)

  // not bad, but I'm not sure if it could handle more bindings at once
  def letWithApp(): Int = let(heavyCalc()) {res => if (cond(res)) doSomethingWithRes(res) else 0}

  List[(String, () => Int)](
    ("withoutLet", withoutLet),
    ("letWithVal", letWithVal),
    ("letWithMatch", letWithMatch),
    ("letWithApp", letWithApp)
  ).foreach(
    item => item match {
      case (title, func) => {
        println(s"executing $title")
        val ret = func()
        println(s"$title finished with $ret")
        println()
      }
    }
  )
}

This is the ideal look of it (with only one binding, more could be separated by ,; not sure about the in keyword):

  // desired look
  def letTest(): Int =
    let res = heavyCalc() in
      if (cond(res)) doSomethingWithRes(res) else 0

I'm not sure if it's possible, but I have no experience with most of advanced Scala stuff like macros, so I can't really tell.

EDIT1: To be clear, the main things I'm expecting from it are: being expression and relatively simple syntax (like the one outlined above).

Это было полезно?

Решение

You could use a forward pipe:

object ForwardPipeContainer {
  implicit class ForwardPipe[A](val value: A) extends AnyVal {
    def |>[B](f: A => B): B = f(value)
  }
}

to be used like this:

import ForwardPipeContainer._

def f(i: Int) = i * i

println( f(3) |> (x => x * x) )

You can put multiple arguments in a tuple:

println( (f(2), f(3)) |> (x => x._1 * x._2) )

which looks better if combined with partial function synatx:

println( (f(2), f(3)) |> { case (x, y) => x * y } )

This answer is a variation of What is a good way of reusing function result in Scala, and both are based on Cache an intermediate variable in an one-liner where I got the initial idea from.

Другие советы

def letTest(): Int =
    let res = heavyCalc() in
      if (cond(res)) doSomethingWithRes(res) else 0

I would write this:

def letTest(): Int = {
  val res = heavyCalc()
  if (cond(res)) doSomethingWithRes(res) else 0
}

Ignoring laziness, let is just a construct that introduces a lexical scope, binds some terms to some names then returns an expression. So in Scala you would do

{ // new lexical scope
  // bind terms section
  val a = f()
  def b = a + g() // may be I don't want g to be evaluated unless b is needed
  val c = h()
  // result expression
  if (c) b else a 
}

Macros should be able to enforce this syntactic layout if you want to ensure that there is nothing else going on in the block. There is actually a SIP (Scala Improvement Process) proposal called Spores that would enforce some of the same constraints (and an additional one: that you don't capture a reference of an enclosing object unknowingly).

Note that blocks in Scala are expressions that evaluate to the last expression in the block. So let me take a random let example from Haskell:

aaa = let y = 1+2
          z = 4+6
          in let f = 3
                 e = 3
             in e+f

This translates to:

val aaa = {
  val y = 1 + 2
  val z = 4 + 6
  val u = {
    val f = 3
    val e = 3
    e + f
  }
  u
}

As you can see the block statement can be used as an expression.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top