Yield - vilinski/nemerle GitHub Wiki

Description

The yield statement is used to implement enumerators. It works by suspending execution of given function and returning (yielding) given result to the function using the enumerator. When the enumerator object is queried again, the function is resumed, until it again executes the yield statement.

The yield foo in Nemerle is equivalent to yield return foo in C#. There is no yield break, though one can just return from a function to achieve this effect.

Restrictions

You cannot use yield in a nested function, unless it eventually expands to a loop.

Examples

using System.Collections.Generic;
using System;

class X {
  public static FromTo (from : int, to : int) : IEnumerable [int]
  {
    for (mutable i = from; i <= to; ++i)
      yield i;
  }

  public static FromTo2 (mutable from : int, to : int) : IEnumerable [int]
  {
    while (from <= to) {
      yield from;
      from++;
    }
  }
}

public class Sequence
{
        public static Concat['a] (
                 first : IEnumerable ['a],
                 second : IEnumerable ['a]) : IEnumerable ['a]
        {
                when (first == null || second == null)
                        throw ArgumentNullException ();

                foreach (element in first)
                        yield element;
                foreach (element in second)
                        yield element;
        }
}
This example uses indentation syntax:
#pragma indent
using System.Collections.Generic
using System

variant Node['a] : IEnumerable['a] \
where 'a : IComparable['a]
  | Elem { l : Node['a]; e : 'a; r : Node['a]; }
  | Nil

  public GetEnumerator () : IEnumerator['a]
    match (this)
      | Elem (l, e, r) =>
        foreach (x in l) yield x;
        yield e;
        foreach (x in r) yield x;
      | Nil => {}

  public Add (e : 'a) : Node['a]
    match (this)
      | Elem (l, e', r) =>
        def c = e.CompareTo (e');
        if (c < 0) Elem (l.Add (e), e', r)
        else if (c > 0) Elem (l, e', r.Add (e))
        else Elem (l, e', r)
      | Nil => Elem (Nil (), e, Nil ())

  public static FromList (e : list ['a]) : Node['a]
    e.FoldLeft (Node.Nil (), fun (e,a) { a.Add (e) })

def n = Node.FromList ([82, 2, 33, 1, 22])
def n2 = Node.FromList (["ene", "due", "rabe", "chinczyk", "zlapal", "zabe"])

foreach (e in n)
  System.Console.WriteLine (e)

foreach (e in n2)
  System.Console.WriteLine (e)
⚠️ **GitHub.com Fallback** ⚠️