Skip to content

for operators #32

Open
Open

Description

@anatoliykmetyuk

Motivation

Case 1: Parsers

In a parser context, assume we have a primitive parser script that accepts a single char, and our goal is to construct another parser script that accepts a range of chars. We want to do this without adding new primitive parser scripts, but by building on top of an existing one:

char(x: Char): Script[Char] = ???
range(start: Char, end: Char) = ???

We'd want:

range('a', 'c') = char('a') + char('b') + char('c')

Another option, of course, is to define range as another parsing primitive (atom), but then alternative will go wrong:

range('a', 'c') foo |+| char('a') bar

Since range is another atom like char, it would be hard to describe that one is a subset of another, even though both may respond to the same event. So we'd prefer something like:

[char('a') + char('b') + char('c')] foo |+| char('a') bar

Case 2: Multithreaded computing with variable number of threads

Consider a computation where we want to run an exact same number of threads as there are cores on the host machine, in parallel:

val numberOfCores = /*determine*/
compute(numberOfCores, data)

We want compute to behave as follows:

if numberOfCores == 2 then {*work(splitData(2).apply(0))*} && {*work(splitData(2).apply(1))*}
else if numberOfCores == 4 then  {*work(splitData(4).apply(0))*} && /* ... */ && {*work(splitData(4).apply(3))*}
else if /*...*/

Very limiting and not DRY approach, obviously.

Case 3: List iterations

We want to do some work for every list element:

var i = 0
while(i < list.size) handle(list(i)) let i += 1

Good, but can be better.

Solution

In case 1, we had to use an + operator, in case 2 - && operator and in case 3 - ; operator. The common thing between all of them is that we don't know the number of their children on compile time.

To address this issue, I propose to introduce a slightly modified for operator.

Definition

The syntax and expansions come in two variants:

for<op>(generators-guards-etc) Term ====> Term(generatedValue1)^ <op> Term(generatedValue2)^ <op> /*...*/ <op> Term(generatedValueN)^

for<op>(generators-guards-etc) yield Term ====> Term(generatedValue1)^^ <op> Term(generatedValue2)^^ <op> /*...*/ <op> Term(generatedValueN)^^

The first syntax is for the nodes that don't yield any result, the second one - for the ones that do return something.

Solutions to the Motivation Problems

Case 1

range(start: Char, end: Char) = for+(c <- start to end) char(c)

Result of for will be the single matched character, because yield is not present.

Case 2

compute(numberOfCores, data) = for&&(pieceOfData <- fork(data, numberOfCores)) yield handle(pieceOfData) ~~^ joinSeqOfResultsTogether

Case 3

listIteration[T](list: Seq[T]) = for;(x: T <- list) yield handle(x)

Prototype

import subscript.language

import subscript._
import subscript.Predef._

import subscript.vm._
import subscript.DSL._

import subscript.vm.model.callgraph._
import subscript.vm.model.template.concrete._
import subscript.vm.model.template._
import subscript.vm.model.template.TemplateNode.Child

object Main extends SubScriptApplication {

  def forPayload(s: Script[Any], doYield: Boolean) =
    (for (x <- 'a' to 'z') yield ([println(x); ^x]))
      .zipWithIndex
      .map {case (c, id) =>
        _at[CallGraphNode, Child](here => {
          implicit val there: CallGraphNode = here.there;
          if (doYield) {
            there.pass = id
            _double_caret(there, s)
          } else _caret(there, s)
        }).apply(_maybeCall("", (here: CallGraphTreeNode) => _maybeVarCall("c")))
      }

  def forScript(op: String, doYield: Boolean) = subscript.DSL._script[Any](None, Symbol("sample")){(_node: subscript.vm.Script[Any]) =>
    implicit val script = _node
    _op(op)(forPayload(script, doYield): _*)
  }

  script..
    live = example1 ~~(x)~~> println: x

    // example1 = for&&(x <- 'a' to 'z') yield [println(x); ^x]
    example1 = forScript("&&", true) // Result: List('a', ..., 'z')

    // example2 = for;(x <- 'a' to 'z') [println(x); ^x]
    example2 = forScript(";", false) // Result: 'z'

}

Activity

  1. anatoliykmetyuk commented on Feb 10, 2016

    @anatoliykmetyuk
    ContributorAuthor

    It has much in common with math sigma (for sum) or product (for product) notation, if you think about it.

  2. AndreVanDelft commented on Feb 12, 2016

    @AndreVanDelft
    Contributor

    I do -currently- not like the proposal for two reasons:

    1. I wanted since many years a for term, much like a while term. So there would be no operator allowed between for and the parenthesized stuff.
    2. The proposed effect of yield: it would surprise me that it would make the result for the enclosing script suddenly a List. I'd rather see such decision explitly through the use of the usual symbol ^^.

    IMO a for construct should be easy to understand, but hard to implement; maybe it would be impossible. for should act much like while, the main difference is that it introduces new variable/value identifiers to the operands to the right, and it initializes these variables/values each time properly.

    A C/Java like for(int i=init; cond; next) construct would translate to:

    var i = if pass==0 then init else i
    let if pass>0 then next
    while cond
    

    Only this should all be done by a single node

    I hope something similar should be possible for a real Scala style for, but I am not sure.
    IMO the generated code will contain the yield construct.

  3. anatoliykmetyuk commented on Feb 19, 2016

    @anatoliykmetyuk
    ContributorAuthor

    I wanted since many years a for term, much like a while term. So there would be no operator allowed between for and the parenthesized stuff.

    Well, why don't we introduce a new keyword for this effect then? For example, sigma, like in math?

    The proposed effect of yield: it would surprise me that it would make the result for the enclosing script suddenly a List. I'd rather see such decision explitly through the use of the usual symbol ^^.

    It is the most intuitive solution, IMO. yield in pure Scala makes its for evaluate to a Seq, so it's most natural for the user to expect the same behaviour from the sigma's yield.

    You're proposing to mimic the for construct after Java/C, as far as I understood. Yet still, Scala's for construct stepped away from the convention adopted by most of the programming languages, and programmers don't seem to suffer from it. Almost everything you can do with Java/C for, you can do with Scala for, even infinite loops if you use Streams or Iterators. Same thing with sigma: anything you can do with for, you can do with sigma (except, maybe, the infinite loops), and even more.

  4. AndreVanDelft commented on Feb 19, 2016

    @AndreVanDelft
    Contributor

    I am still not convinced, but we should start experimenting. It may still be harder than you'd expect.

    Maybe we would not need a new keyword if we want to support both options: just have two variants of for: one with and one without an operator just after for.

    It is nice to see that you can already do new things without touching the preprocessor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions