use std::boxed::Box;
use std::collections::{HashMap, HashSet};

#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
    name: &'a str,
    children: Vec<&'a str>,
    num_parents: usize,
}

fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
    let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();

    for input_line in input {
        let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
        let name = line_split.get(0).unwrap();
        let mut num_parents: usize = 0;
        for parent in line_split.iter().skip(1) {
            if parent == name {
                continue;
            }
            if !libraries.contains_key(parent) {
                libraries.insert(
                    parent,
                    Box::new(Library {
                        name: parent,
                        children: vec![name],
                        num_parents: 0,
                    }),
                );
            } else {
                libraries.get_mut(parent).unwrap().children.push(name);
            }
            num_parents += 1;
        }

        if !libraries.contains_key(name) {
            libraries.insert(
                name,
                Box::new(Library {
                    name,
                    children: Vec::new(),
                    num_parents,
                }),
            );
        } else {
            libraries.get_mut(name).unwrap().num_parents = num_parents;
        }
    }
    libraries
}

fn topological_sort<'a>(
    mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
    let mut needs_processing = libraries
        .iter()
        .map(|(k, _v)| k.clone())
        .collect::<HashSet<&str>>();
    let mut options: Vec<&str> = libraries
        .iter()
        .filter(|(_k, v)| v.num_parents == 0)
        .map(|(k, _v)| *k)
        .collect();
    let mut sorted: Vec<&str> = Vec::new();
    while !options.is_empty() {
        let cur = options.pop().unwrap();
        for children in libraries
            .get_mut(cur)
            .unwrap()
            .children
            .drain(0..)
            .collect::<Vec<&str>>()
        {
            let child = libraries.get_mut(children).unwrap();
            child.num_parents -= 1;
            if child.num_parents == 0 {
                options.push(child.name)
            }
        }
        sorted.push(cur);
        needs_processing.remove(cur);
    }
    match needs_processing.is_empty() {
        true => Ok(sorted),
        false => Err(format!("Cycle detected among {:?}", needs_processing)),
    }
}

fn main() {
    let input: Vec<&str> = vec![
        "des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
        "dw01             ieee dw01 dware gtech dw04\n",
        "dw02             ieee dw02 dware\n",
        "dw03             std synopsys dware dw03 dw02 dw01 ieee gtech\n",
        "dw04             dw04 ieee dw01 dware gtech\n",
        "dw05             dw05 ieee dware\n",
        "dw06             dw06 ieee dware\n",
        "dw07             ieee dware\n",
        "dware            ieee dware\n",
        "gtech            ieee gtech\n",
        "ramlib           std ieee\n",
        "std_cell_lib     ieee std_cell_lib\n",
        "synopsys\n",
    ];

    let libraries = build_libraries(input);
    match topological_sort(libraries) {
        Ok(sorted) => println!("{:?}", sorted),
        Err(msg) => println!("{:?}", msg),
    }
}


(import (chezscheme))
(import (srfi srfi-1))

(define (remove-self-dependency pair)
  (let ((key (car pair))
        (value (cdr pair)))
    (cons key (remq key value))))w

(define (remove-self-dependencies alist)
  (map remove-self-dependency alist))

(define (add-missing-items dependencies)
  (let loop ((items (delete-duplicates (append-map cdr dependencies) eq?))
             (out dependencies))
    (if (null? items)
        out
        (let ((item (car items)))
          (if (assq item out)
              (loop (cdr items) out)
              (loop (cdr items) (cons (cons item '()) out)))))))

(define (lift dependencies batch)
  (let loop ((dependencies dependencies)
             (out '()))
    (if (null? dependencies)
        out
        (let ((key (caar dependencies))
              (value (cdar dependencies)))
          (if (null? value)
              (loop (cdr dependencies) out)
              (loop (cdr dependencies)
                    (cons (cons key (lset-difference eq? value batch))
                          out)))))))

(define (topological-sort dependencies)
  (let* ((dependencies (remove-self-dependencies dependencies))
         (dependencies (add-missing-items dependencies)))
    (let loop ((out '())
               (dependencies dependencies))
      (if (null? dependencies)
          (reverse out)
          (let ((batch (map car (filter (lambda (pair) (null? (cdr pair))) dependencies))))
            (if (null? batch)
                #f
                (loop (cons batch out) (lift dependencies batch))))))))

(define example
  '((des_system_lib . (std synopsys std_cell_lib des_system_lib dw02
                           dw01 ramlib ieee))
    (dw01           . (ieee dw01 dware gtech))
    (dw02           . (ieee dw02 dware))
    (dw03           . (std synopsys dware dw03 dw02 dw01 ieee gtech))
    (dw04           . (dw04 ieee dw01 dware gtech))
    (dw05           . (dw05 ieee dware))
    (dw06           . (dw06 ieee dware))
    (dw07           . (ieee dware))
    (dware          . (ieee dware))
    (gtech          . (ieee gtech))
    (ramlib         . (std ieee))
    (std_cell_lib   . (ieee std_cell_lib))
    (synopsys       . ())))

(write (topological-sort example))

(define unsortable
  '((des_system_lib . (std synopsys std_cell_lib des_system_lib dw02
                           dw01 ramlib ieee))
    (dw01           . (ieee dw01 dware gtech dw04))
    (dw02           . (ieee dw02 dware))
    (dw03           . (std synopsys dware dw03 dw02 dw01 ieee gtech))
    (dw04           . (dw04 ieee dw01 dware gtech))
    (dw05           . (dw05 ieee dware))
    (dw06           . (dw06 ieee dware))
    (dw07           . (ieee dware))
    (dware          . (ieee dware))
    (gtech          . (ieee gtech))
    (ramlib         . (std ieee))
    (std_cell_lib   . (ieee std_cell_lib))
    (synopsys       . ())))

(newline)
(write (topological-sort unsortable))


function test() {
    let n = 0
    for(let i = 0; i < 1000000; i++){
        n += i
    }
}

let start = new Date().valueOf()
test()
let end = new Date().valueOf()

console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds


# v0.6.0

function countto(n::Integer)
    i = zero(n)
    println("Counting...")
    while i < n
        i += 1
    end
    println("Done!")
end

@time countto(10 ^ 5)
@time countto(10 ^ 10)


// version 1.1.2
// need to enable runtime assertions with JVM -ea option

import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean

fun countTo(x: Int) {
    println("Counting...");
    (1..x).forEach {}
    println("Done!")
}

fun main(args: Array<String>) {
    val counts = intArrayOf(100_000_000, 1_000_000_000)
    val threadMX = ManagementFactory.getThreadMXBean()
    assert(threadMX.isCurrentThreadCpuTimeSupported)
    threadMX.isThreadCpuTimeEnabled = true
    for (count in counts) {
        val start = threadMX.currentThreadCpuTime
        countTo(count)
        val end = threadMX.currentThreadCpuTime
        println("Counting to $count takes ${(end-start)/1000000}ms")
    }
}


import java.util.*;

public class TreeTraversal {

        static class Node<T> {
		T value;
		Node<T> left;
		Node<T> right;

		Node(T value) {
			this.value = value;
		}

		void visit() {
			System.out.print(this.value + " ");
		}
	}

	static enum ORDER {
		PREORDER, INORDER, POSTORDER, LEVEL
	}

        static <T> void traverse(Node<T> node, ORDER order) {
		if (node == null) {
			return;
		}
		switch (order) {
		case PREORDER:
			node.visit();
			traverse(node.left, order);
			traverse(node.right, order);
			break;
		case INORDER:
			traverse(node.left, order);
			node.visit();
			traverse(node.right, order);
			break;
		case POSTORDER:
			traverse(node.left, order);
			traverse(node.right, order);
			node.visit();
			break;
		case LEVEL:
			Queue<Node<T>> queue = new LinkedList<>();
			queue.add(node);
			while(!queue.isEmpty()){
				Node<T> next = queue.remove();
				next.visit();
				if(next.left!=null)
					queue.add(next.left);
				if(next.right!=null)
					queue.add(next.right);
			}
		}
	}

	public static void main(String[] args) {

		Node<Integer> one = new Node<Integer>(1);
		Node<Integer> two = new Node<Integer>(2);
		Node<Integer> three = new Node<Integer>(3);
		Node<Integer> four = new Node<Integer>(4);
		Node<Integer> five = new Node<Integer>(5);
		Node<Integer> six = new Node<Integer>(6);
		Node<Integer> seven = new Node<Integer>(7);
		Node<Integer> eight = new Node<Integer>(8);
		Node<Integer> nine = new Node<Integer>(9);

		one.left = two;
		one.right = three;
		two.left = four;
		two.right = five;
		three.left = six;
		four.left = seven;
		six.left = eight;
		six.right = nine;

		traverse(one, ORDER.PREORDER);
		System.out.println();
		traverse(one, ORDER.INORDER);
		System.out.println();
		traverse(one, ORDER.POSTORDER);
		System.out.println();
		traverse(one, ORDER.LEVEL);

	}
}


	org	100h
	jmp	demo
	;;;	Routine to split a 0-terminated string
	;;;	Input: B=separator, C=escape, HL=string pointer.
	;;;	Output: DE=end of list of strings
	;;;	The split strings are stored in place.
split:	mov	d,h	; Set DE = output pointer
	mov	e,l
snext:	mov	a,m	; Get current input character
	inx	h	; Advance input pointer
	stax	d	; Write character at output pointer
	ana	a	; If zero, we are done
	rz
	cmp	c	; Is it the escape character?
	jz	sesc
	cmp	b	; Is it the separator character?
	jz	ssep
	inx	d	; Otherwise, advance output pointer,
	jmp	snext	; and get the next character
sesc:	mov	a,m	; Store the escaped character without
	inx	h	; checking for anything except zero.
	stax	d
	inx	d
	ana	a	; Zero is still end of string
	rz
	jmp	snext
ssep:	xra 	a	; End of string, write zero terminator
	stax	d
	inx	d
	jmp	snext
	;;;	Use the routine to split the test-case string
demo:	mvi	b,'|'	; Separator character
	mvi	c,'^'	; Escape character
	lxi	h,test	; Pointer to test string
	call	split
	;;;	Print each string on its own line
	lxi	h,test
str:	call	puts	; Print string
	call	cmp16	; Are we there yet?
	jnc	str	; If not, print the next string
	ret
	;;;	16-bit compare
cmp16:	mov	a,d
	cmp	h
	rnz
	mov	a,e
	cmp	l
	ret
	;;;	Print zero-terminated string with newline
puts:	push	d	; Keep DE registers
	push	h	; Keep pointer
	lxi 	d,pfx	; Print prefix
	mvi	c,9
	call	5
	pop	h	; Restore pointer
ploop:	mov	e,m	; Get current character
	push	h	; Keep pointer
	mvi	c,2	; CP/M print character
	call	5
	pop	h	; Restore pointer
	mov	a,m	; Is character zero?
	ora	a
	inx	h	; Increment pointer
	jnz	ploop	; If not, there are more characters
	push	h	; Keep pointer
	lxi	d,nl	; Write newline
	mvi	c,9	; CP/M print string
	call	5
	pop	h
	pop	d	; Restore DE registers
	ret
pfx:	db	'> $'	; Prefix to make the output more obvious
nl:	db	13,10,'$'
test:	db	'one^|uno||three^^^^|four^^^|^cuatro|',0


DEFINE PTR="CARD"

TYPE Tokens=[
  PTR buf   ;BYTE ARRAY
  PTR arr   ;CARD ARRAY
  PTR endPtr
  BYTE count]

PROC Init(Tokens POINTER t BYTE ARRAY b PTR ARRAY a)
  t.buf=b
  t.arr=a
  t.endPtr=b
  t.count=0
RETURN

PROC AddToken(Tokens POINTER t CHAR ARRAY s)
  PTR ARRAY a
  CHAR ARRAY tmp

  a=t.arr
  tmp=t.endPtr
  SCopy(tmp,s)
  a(t.count)=tmp
  t.count==+1
  t.endPtr=t.endPtr+s(0)+1
RETURN

PROC PrintTokens(Tokens POINTER t)
  BYTE i
  PTR ARRAY a

  a=t.arr
  FOR i=0 TO t.count-1
  DO
    PrintF("""%S""%E",a(i))
  OD
RETURN

PROC Append(CHAR ARRAY s CHAR c)
  s(0)==+1
  s(s(0))=c
RETURN

PROC Tokenize(CHAR ARRAY s CHAR sep,esc Tokens POINTER res)
  BYTE ARRAY b(200)
  PTR ARRAY a(20)
  CHAR ARRAY tmp(255)
  BYTE i,isEsc
  CHAR c

  Init(res,b,a)
  isEsc=0
  tmp(0)=0
  FOR i=1 TO s(0)
  DO
    c=s(i)
    IF isEsc THEN
      isEsc=0
      Append(tmp,c)
    ELSE
      IF c=esc THEN
        isEsc=1
      ELSEIF c=sep THEN
        AddToken(res,tmp)
        tmp(0)=0
      ELSE
        Append(tmp,c)
      FI
    FI
  OD
  AddToken(res,tmp)
RETURN

PROC Main()
  Tokens t

  Tokenize("one^|uno||three^^^^|four^^^|^cuatro|",'|,'^,t)
  PrintTokens(t)
RETURN


with Ada.Text_Io;
with Ada.Containers.Indefinite_Vectors;
with Ada.Strings.Unbounded;

procedure Tokenize is

   package String_Vectors is
     new Ada.Containers.Indefinite_Vectors (Positive, String);
   use String_Vectors;

   function Split (Text      : String;
                   Separator : Character := '|';
                   Escape    : Character := '^') return Vector
   is
      use Ada.Strings.Unbounded;
      Result  : Vector;
      Escaped : Boolean := False;
      Accu    : Unbounded_String;
   begin

      for Char of Text loop

         case Escaped is

            when False =>
               if Char = Escape then
                  Escaped := True;
               elsif Char = Separator then
                  Append (Result, To_String (Accu));
                  Accu := Null_Unbounded_String;
               else
                  Append (Accu, Char);
               end if;

            when True =>
               Append (Accu, Char);
               Escaped := False;

         end case;

      end loop;
      Append (Result, To_String (Accu));

      return Result;
   end Split;

   procedure Put_Vector (List : Vector) is
      use Ada.Text_Io;
   begin
      for Element of List loop
         Put ("'"); Put (Element); Put ("'"); New_Line;
      end loop;
   end Put_Vector;

begin
   Put_Vector (Split ("one^|uno||three^^^^|four^^^|^cuatro|"));
end Tokenize;


func print_topo_sort (deps) {
    var ba = Hash.new;
    deps.each { |before, afters|
        afters.each { |after|
            if (before != after) {
                ba{before}{after} = 1;
            };
            ba{after} \\= Hash.new;
        }
    };

    loop {
        var afters = ba.keys.grep {|k| ba{k}.values.len == 0 }.sort;
        afters.len || break;
        say afters.join(" ");
        ba.delete(afters...);
        ba.values.each { |v| v.delete(afters...) };
    };

    say (ba.len ? "Cicle found! #{ba.keys.sort}" : "---");
}

var deps = Hash.new(
    des_system_lib => < std synopsys std_cell_lib des_system_lib dw02
                                                     dw01 ramlib ieee >,
    dw01           => < ieee dw01 dware gtech                         >,
    dw02           => < ieee dw02 dware                               >,
    dw03           => < std synopsys dware dw03 dw02 dw01 ieee gtech  >,
    dw04           => < dw04 ieee dw01 dware gtech                    >,
    dw05           => < dw05 ieee dware                               >,
    dw06           => < dw06 ieee dware                               >,
    dw07           => < ieee dware                                    >,
    dware          => < ieee dware                                    >,
    gtech          => < ieee gtech                                    >,
    ramlib         => < std ieee                                      >,
    std_cell_lib   => < ieee std_cell_lib                             >,
    synopsys       => <                                               >
);

print_topo_sort(deps);
deps{:dw01}.append('dw04');     # Add unresolvable dependency
print_topo_sort(deps);


local(start = micros)
loop(100000) => {
	'nothing is outout because no autocollect'
}
'time for 100,000 loop repititions: '+(micros - #start)+' microseconds'


on testFunc ()
  repeat with i = 1 to 1000000
    x = sqrt(log(i))
  end repeat
end


to time
  output first first shell "|date +%s|
end
to elapsed :block
  localmake "start time
  run :block
  (print time - :start [seconds elapsed])
end

elapsed [wait 300]   ; 5 seconds elapsed


function Test_Function()
    for i = 1, 10000000 do
        local s = math.log( i )
        s = math.sqrt( s )
    end
end

t1 = os.clock()
    Test_Function()
t2 = os.clock()

print( os.difftime( t2, t1 ) )


Module Checkit {
      Module sumtolimit (limit) {
           sum=limit-limit
           n=sum
           n++
           while limit {sum+=limit*n:limit--:n-!}
      }
      Cls ' clear screen
      Profiler
      sumtolimit 10000%
      Print TimeCount
      Profiler
      sumtolimit 10000&
      Print TimeCount
      Profiler
      sumtolimit 10000#
      Print TimeCount
      Profiler
      sumtolimit [email protected]
      Print TimeCount
      Profiler
      sumtolimit 10000~
      Print TimeCount
      Profiler
      sumtolimit 10000
      Print TimeCount
}
Checkit


function BinaryTree(value, left, right) {
    this.value = value;
    this.left = left;
    this.right = right;
}
BinaryTree.prototype.preorder  = function(f) {this.walk(f,['this','left','right'])}
BinaryTree.prototype.inorder   = function(f) {this.walk(f,['left','this','right'])}
BinaryTree.prototype.postorder = function(f) {this.walk(f,['left','right','this'])}
BinaryTree.prototype.walk = function(func, order) {
    for (var i in order)
        switch (order[i]) {
            case "this": func(this.value); break;
            case "left": if (this.left) this.left.walk(func, order); break;
            case "right": if (this.right) this.right.walk(func, order); break;
        }
}
BinaryTree.prototype.levelorder = function(func) {
    var queue = [this];
    while (queue.length != 0) {
        var node = queue.shift();
        func(node.value);
        if (node.left) queue.push(node.left);
        if (node.right) queue.push(node.right);
    }
}

// convenience function for creating a binary tree
function createBinaryTreeFromArray(ary) {
    var left = null, right = null;
    if (ary[1]) left = createBinaryTreeFromArray(ary[1]);
    if (ary[2]) right = createBinaryTreeFromArray(ary[2]);
    return new BinaryTree(ary[0], left, right);
}

var tree = createBinaryTreeFromArray([1, [2, [4, [7]], [5]], [3, [6, [8],[9]]]]);

print("*** preorder ***");   tree.preorder(print);
print("*** inorder ***");    tree.inorder(print);
print("*** postorder ***");  tree.postorder(print);
print("*** levelorder ***"); tree.levelorder(print);


BEGIN
    # returns s parsed according to delimiter and escape                      #
    PROC parse with escapes = ( STRING s, CHAR delimiter, escape )[]STRING:
         IF ( UPB s - LWB s ) + 1 < 1 THEN
            # empty string                                                    #
            [ 1 : 0 ]STRING empty array;
            empty array
         ELSE
            # at least one character                                          #
            # allow for a string composed entirely of delimiter characters    #
            [ 1 : ( UPB s - LWB s ) + 3 ]STRING result;
            INT r pos := 1;
            INT s pos := LWB s;
            result[ r pos ] := "";
            WHILE s pos <= UPB s DO
                CHAR c = s[ s pos ];
                IF  c = delimiter THEN
                    # start a new element                                     #
                    result[ r pos +:= 1 ] := ""
                ELIF c = escape THEN
                    # use the next character even if it is an escape          #
                    s pos +:= 1;
                    IF s pos < UPB s THEN
                        # the escape is not the last character                #
                        result[ r pos ] +:= s[ s pos ]
                    FI
                ELSE
                    # normal character                                        #
                    result[ r pos ] +:= c
                FI;
                s pos +:= 1
            OD;
            result[ 1 : r pos ]
         FI; # parse with escapes #
    # task test case                                                          #
    []STRING tokens = parse with escapes( "one^|uno||three^^^^|four^^^|^cuatro|", "|", "^" );
    FOR t pos FROM LWB tokens TO UPB tokens DO print( ( "[", tokens[ t pos ], "]", newline ) ) OD
END


------------------ TOKENIZE WITH ESCAPING ----------------

-- tokenize :: String -> Character -> Character -> [String]
on tokenize(str, delimChar, chrEsc)

    script charParse
        -- Record: {esc:Bool, token:String, tokens:[String]}
        -- charParse :: Record -> Character -> Record
        on |λ|(a, x)
            set blnEsc to esc of a
            set blnEscChar to ((not blnEsc) and (x = chrEsc))

            if ((not blnEsc) and (x = delimChar)) then
                set k to ""
                set ks to (tokens of a) & token of a
            else
                set k to (token of a) & cond(blnEscChar, "", x)
                set ks to tokens of (a)
            end if

            {esc:blnEscChar, token:k, tokens:ks}
        end |λ|
    end script

    set recParse to foldl(charParse, ¬
        {esc:false, token:"", tokens:[]}, splitOn("", str))

    tokens of recParse & token of recParse
end tokenize

--------------------------- TEST -------------------------
on run
    script numberedLine
        on |λ|(a, s)
            set iLine to lineNum of a
            {lineNum:iLine + 1, report:report of a & iLine & ":" & tab & s & linefeed}
        end |λ|
    end script

    report of foldl(numberedLine, {lineNum:1, report:""}, ¬
        tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^"))
end run

-------------------- GENERIC FUNCTIONS -------------------

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- splitOn :: String -> String -> [String]
on splitOn(pat, src)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, pat}
    set xs to text items of src
    set my text item delimiters to dlm
    return xs
end splitOn

-- cond :: Bool -> a -> a -> a
on cond(bool, f, g)
    if bool then
        f
    else
        g
    end if
end cond


let libs = [
  ("des_system_lib", ["std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"]),
  ("dw01", ["ieee", "dw01", "dware", "gtech"]),
  ("dw02", ["ieee", "dw02", "dware"]),
  ("dw03", ["std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"]),
  ("dw04", ["dw04", "ieee", "dw01", "dware", "gtech"]),
  ("dw05", ["dw05", "ieee", "dware"]),
  ("dw06", ["dw06", "ieee", "dware"]),
  ("dw07", ["ieee", "dware"]),
  ("dware", ["ieee", "dware"]),
  ("gtech", ["ieee", "gtech"]),
  ("ramlib", ["std", "ieee"]),
  ("std_cell_lib", ["ieee", "std_cell_lib"]),
  ("synopsys", [])
]

struct Library {
  var name: String
  var children: [String]
  var numParents: Int
}

func buildLibraries(_ input: [(String, [String])]) -> [String: Library] {
  var libraries = [String: Library]()

  for (name, parents) in input {
    var numParents = 0

    for parent in parents where parent != name {
      numParents += 1

      libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)
    }

    libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents
  }

  return libraries
}

func topologicalSort(libs: [String: Library]) -> [String]? {
  var libs = libs
  var needsProcessing = Set(libs.keys)
  var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil })
  var sorted = [String]()

  while let cur = options.popLast() {
    for children in libs[cur]?.children ?? [] {
      libs[children]?.numParents -= 1

      if libs[children]?.numParents == 0 {
        options.append(libs[children]!.name)
      }
    }

    libs[cur]?.children.removeAll()

    sorted.append(cur)
    needsProcessing.remove(cur)
  }

  guard needsProcessing.isEmpty else {
    return nil
  }

  return sorted
}

print(topologicalSort(libs: buildLibraries(libs))!)


data node <'.+'>, from <node>, to <node>

templates topologicalSort
  @: [];
  {V: {|$.v..., $.e({node: §.to})...|} , E: {|$.e... -> \(<{from: <~=$.to>}> $! \)|}} -> #
  when <{V: <?($::count <=0>)>}> [email protected]!
  otherwise
    def independent: ($.V notMatching $.E({node: §.from}));
    [$independent... -> $.node] -> ..|@: $;
    {V: ($.V notMatching $independent), E: ($.E notMatching $independent({to: §.node}))}
    -> \(<?($independent::count <1..>)> $! \) -> #
end topologicalSort

composer lines
  [<line>+]
  rule line: <'[^\n]*'> (<'\n'>)
end lines

templates collectDeps
  @: { v: [], e: []};
  composer depRecord
    (<WS>? def node: <~WS>; <WS>? <dep>* <WS>? $node -> ..|@collectDeps.v: {node: $};)
    rule dep: (<~WS> -> ..|@collectDeps.e: {from: $node, to: $}; <WS>?)
  end depRecord
  $(3..last)... -> !depRecord
  [email protected]!
end collectDeps

'LIBRARY          LIBRARY DEPENDENCIES
            =======          ====================
            des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
            dw01             ieee dw01 dware gtech
            dw02             ieee dw02 dware
            dw03             std synopsys dware dw03 dw02 dw01 ieee gtech
            dw04             dw04 ieee dw01 dware gtech
            dw05             dw05 ieee dware
            dw06             dw06 ieee dware
            dw07             ieee dware
            dware            ieee dware
            gtech            ieee gtech
            ramlib           std ieee
            std_cell_lib     ieee std_cell_lib
            synopsys
' -> lines -> collectDeps -> topologicalSort -> !OUT::write


CodeTools:-Usage(ifactor(32!+1), output = realtime, quiet);


f(n) := if n < 2 then n else f(n - 1) + f(n - 2)$

/* First solution, call the time function with an output line number, it gives the time taken to compute that line.
   Here it's assumed to be %o2 */
f(24);
46368

time(%o2);
[0.99]

/* Second solution, change a system flag to print timings for all following lines */
showtime: true$

f(24);
Evaluation took 0.9400 seconds (0.9400 elapsed)
46368


start = time
for i in range(1,100000)
end for
duration = time - start
print "Process took " + duration + " seconds"


import times, strutils

proc doWork(x: int) =
  var n = x
  for i in 0..10000000:
    n += i

template time(statement: untyped): float =
  let t0 = cpuTime()
  statement
  cpuTime() - t0

echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s"


let time_it action arg =
  let start_time = Sys.time () in
  ignore (action arg);
  let finish_time = Sys.time () in
  finish_time -. start_time


V text = ‘Hello,How,Are,You,Today’
V tokens = text.split(‘,’)
print(tokens.join(‘.’))


def preorder:
  if length == 0 then empty
  else .[0], (.[1]|preorder), (.[2]|preorder)
  end;

def inorder:
  if length == 0 then empty
  else (.[1]|inorder), .[0] , (.[2]|inorder)
  end;

def postorder:
  if length == 0 then empty
  else (.[1] | postorder), (.[2]|postorder), .[0]
  end;

# Helper functions for levelorder:
  # Produce a stream of the first elements
  def heads: map( .[0] | select(. != null)) | .[];

# Produce a stream of the left/right branches:
  def tails:
    if length == 0 then empty
    else [map ( .[1], .[2] ) | .[] | select( . != null)]
    end;

def levelorder: [.] | recurse( tails ) | heads;


tokenize: function [s sep esc][
	escaping: 0

	loop 0..(size s)-1 [i][
		chr: get split s i

		if? escaping=1 [
			prints chr
			escaping: 0
		]
		else [
			case [chr]
				when? [=sep] [print ""]
				when? [=esc] [escaping: 1]
				else [prints chr]
		]
	]
	print ""
]

str: "one^|uno||three^^^^|four^^^|^cuatro|"
tokenize str "|" "^"


Tokenize(s,d,e){
	for i,v in x:=StrSplit(StrReplace(StrReplace(StrReplace(s,e e,Chr(0xFFFE)),e d,Chr(0xFFFF)),e),d)
		x[i]:=StrReplace(StrReplace(v,Chr(0xFFFE),e),Chr(0xFFFF),d)
	return x
}


REM >tokenizer
PROC_tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^")
END
:
DEF PROC_tokenize(src$, sep$, esc$)
LOCAL field%, char$, escaping%, i%
field% = 1
escaping% = FALSE
PRINT field%; " ";
FOR i% = 1 TO LEN src$
  char$ = MID$(src$, i%, 1)
  IF escaping% THEN
    PRINT char$;
    escaping% = FALSE
  ELSE
    CASE char$ OF
    WHEN sep$
      PRINT
      field% += 1
      PRINT field%; " ";
    WHEN esc$
      escaping% = TRUE
    OTHERWISE
      PRINT char$;
    ENDCASE
  ENDIF
NEXT
PRINT
ENDPROC


str ← "one^|uno||three^^^^|four^^^|^cuatro|"
Split ← ((⊢-˜+`×¬)∘=⊔⊢)
SplitE ← {
  esc ← <`'^'=𝕩
  rem ← »esc
  spl ← (¬rem)∧'|'=𝕩
  𝕩⊔˜(⊢-(esc∨spl)×1⊸+)+`spl
}

•Show SplitE str


package require Tcl 8.5
proc topsort {data} {
    # Clean the data
    dict for {node depends} $data {
	if {[set i [lsearch -exact $depends $node]] >= 0} {
	    set depends [lreplace $depends $i $i]
	    dict set data $node $depends
	}
	foreach node $depends {dict lappend data $node}
    }
    # Do the sort
    set sorted {}
    while 1 {
	# Find available nodes
	set avail [dict keys [dict filter $data value {}]]
	if {![llength $avail]} {
	    if {[dict size $data]} {
		error "graph is cyclic, possibly involving nodes \"[dict keys $data]\""
	    }
	    return $sorted
	}
	# Note that the lsort is only necessary for making the results more like other langs
	lappend sorted {*}[lsort $avail]
        # Remove from working copy of graph
	dict for {node depends} $data {
	    foreach n $avail {
		if {[set i [lsearch -exact $depends $n]] >= 0} {
		    set depends [lreplace $depends $i $i]
		    dict set data $node $depends
		}
	    }
	}
	foreach node $avail {
	    dict unset data $node
	}
    }
}


declare
  %% returns milliseconds
  fun {TimeIt Proc}
     Before = {Now}
  in
     {Proc}
     {Now} - Before
  end

  fun {Now}
     {Property.get 'time.total'}
  end
in
  {Show
   {TimeIt
    proc {$}
       {FoldL {List.number 1 1000000 1} Number.'+' 4 _}
    end}
  }


use Benchmark;
use Memoize;

sub fac1 {
    my $n = shift;
    return $n == 0 ? 1 : $n * fac1($n - 1);
}
sub fac2 {
    my $n = shift;
    return $n == 0 ? 1 : $n * fac2($n - 1);
}
memoize('fac2');

my $result = timethese(100000, {
    'fac1' => sub { fac1(50) },
    'fac2' => sub { fac2(50) },
});
Benchmark::cmpthese($result);


*        Tokenize a string -       08/06/2018
TOKSTR   CSECT
         USING  TOKSTR,R13         base register
         B      72(R15)            skip savearea
         DC     17F'0'             savearea
         SAVE   (14,12)            save previous context
         ST     R13,4(R15)         link backward
         ST     R15,8(R13)         link forward
         LR     R13,R15            set addressability
         MVC    N,=A(1)            n=1
         LA     R7,1               i1=1
         LA     R6,1               i=1
       DO WHILE=(C,R6,LE,LENS)     do i=1 to length(s);
         LA     R4,S-1             @s-1
         AR     R4,R6              +i
         MVC    C,0(R4)            c=substr(s,i,1)
       IF CLI,C,EQ,C',' THEN       if c=',' then do
         BAL    R14,TOK              call tok
         LR     R2,R8                i2
         SR     R2,R7                i2-i1
         LA     R2,1(R2)             i2-i1+1
         L      R1,N                 n
         SLA    R1,1                 *2
         STH    R2,TALEN-2(R1)       talen(n)=i2-i1+1
         L      R2,N                 n
         LA     R2,1(R2)             n+1
         ST     R2,N                 n=n+1
         LA     R7,1(R6)             i1=i+1
       ENDIF    ,                    endif
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         BAL    R14,TOK            call tok
         LR     R2,R8              i2
         SR     R2,R7              i2-i1
         LA     R2,1(R2)           i2-i1+1
         L      R1,N               n
         SLA    R1,1               *2
         STH    R2,TALEN-2(R1)     talen(n)=i2-i1+1
         LA     R11,PG             [email protected]
         LA     R6,1               i=1
       DO WHILE=(C,R6,LE,N)        do i=1 to n
         LR     R1,R6                i
         SLA    R1,1                 *2
         LH     R10,TALEN-2(R1)      l=talen(i)
         LR     R1,R6                i
         SLA    R1,3                 *8
         LA     R4,TABLE-8(R1)       @table(i)
         LR     R2,R10               l
         BCTR   R2,0                 ~
         EX     R2,MVCX              output table(i) length(l)
         AR     R11,R10              pgi=pgi+l
       IF C,R6,NE,N THEN             if i^=n then
         MVC    0(1,R11),=C'.'         output '.'
         LA     R11,1(R11)             pgi=pgi+1
       ENDIF    ,                    endif
         LA     R6,1(R6)             i++
       ENDDO    ,                  enddo i
         XPRNT  PG,L'PG            print
         L      R13,4(0,R13)       restore previous savearea pointer
         RETURN (14,12),RC=0       restore registers from calling sav
TOK      LR     R5,R6              i                              <--
         BCTR   R5,0               i-1                              |
         LR     R8,R5              i2=i-1
         SR     R5,R7              i2-i1
         LA     R5,1(R5)           l=i2-i1+1  source length
         L      R1,N               n
         SLA    R1,3               *8
         LA     R2,TABLE-8(R1)     @table(n)
         LA     R4,S-1             @s-1
         AR     R4,R7              @s+i1-1
         LA     R3,8               target length
         MVCL   R2,R4              table(n)=substr(s,i1,i2-i1+1)    |
         BR     R14                End TOK subroutine             <--
MVCX     MVC    0(0,R11),0(R4)     output table(i)
S        DC     CL80'Hello,How,Are,You,Today'  <== input string ==
LENS     DC     F'23'              length(s)   <==
TABLE    DC     8CL8' '            table(8)
TALEN    DC     8H'0'              talen(8)
C        DS     CL1                char
N        DS     F                  number of tokens
PG       DC     CL80' '            buffer
         YREGS
         END    TOKSTR


puts:	equ	9
	org	100h
	jmp	demo
	;;;	Split the string at DE by the character in C.
	;;;	Store pointers to the beginning of the elements starting at HL
	;;;	The amount of elements is returned in B.
split:	mvi	b,0		; Amount of elements
sloop:	mov	m,e		; Store pointer at [HL]
	inx	h
	mov	m,d
	inx	h
	inr	b		; Increment counter
sscan:	ldax	d		; Get current character
	inx	d
	cpi	'$'		; Done?
	rz			; Then stop
	cmp	c		; Place to split?
	jnz	sscan		; If not, keep going
	dcx	d
	mvi	a,'$'		; End the string here
	stax	d
	inx	d
	jmp	sloop		; Next part
	;;;	Test on the string given in the task
demo:	lxi	h,parts		; Parts array
	lxi	d,hello		; String
	mvi	c,','
	call 	split		; Split the string
	lxi	h,parts		; Print each part
loop:	mov	e,m		; Load pointer into DE
	inx	h
	mov	d,m
	inx	h
	push	h		; Keep the array pointer
	push	b		; And the counter
	mvi	c,puts 		; Print the string
	call	5
	lxi	d,period	; And a period
	mvi	c,puts
	call 	5
	pop 	b		; Restore the counter
	pop 	h		; Restore the array pointer
	dcr	b 		; One fewer string left
	jnz 	loop
	ret
period:	db	'. $'
hello:	db	'Hello,How,Are,You,Today$'
parts:	equ	$


	cpu	8086
	org	100h
section	.text
	jmp	demo
	;;;	Split the string at DS:SI on the character in DL.
	;;;	Store pointers to strings starting at ES:DI.
	;;;	The amount of strings is returned in CX.
split:	xor	cx,cx		; Zero out counter
.loop:	mov	ax,si		; Store pointer to current location
	stosw
	inc	cx		; Increment counter
.scan:	lodsb			; Get byte
	cmp	al,'$'		; End of string?
	je	.done
	cmp	al,dl		; Character to split on?
	jne	.scan
	mov	[si-1],byte '$'	; Terminate string
	jmp	.loop
.done:	ret
	;;;	Test on the string given in the task
demo:	mov	si,hello	; String to split
	mov	di,parts	; Place to store pointers
	mov	dl,','		; Character to split string on
	call	split
	;;;	Print the resulting strings, and periods
	mov	si,parts	; Array of string pointers
print:	lodsw			; Load next pointer
	mov	dx,ax		; Print string using DOS
	mov	ah,9
	int	21h
	mov	dx,period	; Then print a period
	int	21h
	loop	print		; Loop while there are strings
	ret
section .data
period:	db	'. $'
hello:	db	'Hello,How,Are,You,Today$'
section	.bss
parts:	resw	10


tree = Any[1, Any[2, Any[4, Any[7, Any[],
                                          Any[]],
                                   Any[]],
                            Any[5, Any[],
                                   Any[]]],
                     Any[3, Any[6, Any[8, Any[],
                                          Any[]],
                                   Any[9, Any[],
                                          Any[]]],
                            Any[]]]

preorder(t, f) = if !isempty(t)
                     f(t[1]); preorder(t[2], f); preorder(t[3], f)
                 end

inorder(t, f) = if !isempty(t)
                    inorder(t[2], f); f(t[1]); inorder(t[3], f)
                end

postorder(t, f) = if !isempty(t)
                      postorder(t[2], f); postorder(t[3], f); f(t[1])
                  end

levelorder(t, f) = while !isempty(t)
                       t = mapreduce(x -> isa(x, Number) ? (f(x); []) : x, vcat, t)
                   end


#include <stdlib.h>
#include <stdio.h>

#define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|"
#define SEP '|'
#define ESC '^'

typedef char* Str; /* just for an easier reading */

/* ===> FUNCTION PROTOTYPES <================================================ */
unsigned int ElQ( const char *s, char sep, char esc );
Str *Tokenize( char *s, char sep, char esc, unsigned int *q );

/*==============================================================================
Main function.
Just passes a copy of the STR_DEMO string to the tokenization function and shows
the results.
==============================================================================*/

int main() {
    char s[] = STR_DEMO;
    unsigned int i, q;

    Str *list = Tokenize( s, SEP, ESC, &q );

    if( list != NULL ) {
        printf( "\n Original string: %s\n\n", STR_DEMO );
        printf( " %d tokens:\n\n", q );

        for( i=0; i<q; ++i )
            printf( " %4d. %s\n", i+1, list[i] );

        free( list );
    }

    return 0;
}

/*==============================================================================
"ElQ" stands for "Elements Quantity". Counts the amount of valid element in the
string s, according to the separator character provided in sep and the escape
character provided in esc.
==============================================================================*/

unsigned int ElQ( const char *s, char sep, char esc ) {
    unsigned int q, e;
    const char *p;

    for( e=0, q=1, p=s; *p; ++p ) {
        if( *p == esc )
            e = !e;
        else if( *p == sep )
            q += !e;
        else e = 0;
    }

    return q;
}

/*==============================================================================
The actual tokenization function.
Allocates as much dynamic memory as needed to contain the pointers to the
tokenized portions of the string passed as the "s" parameter, then looks for the
separators characters sep, paying attention to the occurrences of the escape
character provided in esc. When a valid separator is found, the function swaps
it with a '\0' terminator character and stores the pointer to the next string
into the array of pointers in dynamic memory. On output, the value of *q is the
number of pointers in the array. The caller is responsible for deallocating with
free() the returned array of pointers when it is no longer needed.
In case of failure, NULL is returned.
==============================================================================*/

Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) {
    Str *list = NULL;

    *q = ElQ( s, sep, esc );
    list = malloc( *q * sizeof(Str) );

    if( list != NULL ) {
        unsigned int e, i;
        char *p;

        i = 0;
        list[i++] = s;

        for( e=0, p=s; *p; ++p ) {
            if( *p == esc ) {
                e = !e;
            }
            else if( *p == sep && !e ) {
                list[i++] = p+1;
                *p = '\0';
            }
            else {
                e = 0;
            }
        }
    }

    return list;
}


$ awk '{ for (i = 1; i <= NF; i++) print $i, $1 }' <<! | tsort
> des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
> dw01             ieee dw01 dware gtech
> dw02             ieee dw02 dware
> dw03             std synopsys dware dw03 dw02 dw01 ieee gtech
> dw04             dw04 ieee dw01 dware gtech
> dw05             dw05 ieee dware
> dw06             dw06 ieee dware
> dw07             ieee dware
> dware            ieee dware
> gtech            ieee gtech
> ramlib           std ieee
> std_cell_lib     ieee std_cell_lib
> synopsys
> !
ieee
dware
dw02
dw05
dw06
dw07
gtech
dw01
dw04
std_cell_lib
synopsys
std
dw03
ramlib
des_system_lib


tsort = ~&nmnNCjA*imSLs2nSjiNCSPT; @NiX ^=lxPrnSPX ^(~&rlPlT,~&rnPrmPljA*[email protected])^|/~& ~&m!=rnSPlX


with javascript_semantics
function identity(integer x)
    return x
end function

function total(integer num)
    for i=1 to 100_000_000 do
        num += odd(i)
    end for
    return num
end function

procedure time_it(integer fn)
    atom t0 = time()
    integer res = fn(4)
    string funcname = get_routine_info(fn)[4]
    printf(1,"%s(4) = %d, taking %s\n",{funcname,res,elapsed(time()-t0)})
end procedure

time_it(identity)
time_it(total)


def count
	for drop endfor
enddef

1000000 count
msec dup var t0 print " seconds" print nl

10000000 count
msec t0 - print " seconds" print


import cp.

go =>
  println("time/1 for 201 queens:"),
  time2(once(queens(201,_Q))),
  nl,

  % time1b/1 is a used defined function (using statistics/2)
  Time = time1b($once(queens(28,Q2))),
  println(Q2),
  printf("28-queens took %dms\n", Time),
  nl.

% N-queens problem.
% N: number of queens to place
% Q: the solution
queens(N, Q) =>
    Q=new_list(N),
    Q :: 1..N,
    all_different(Q),
    all_different([$Q[I]-I : I in 1..N]),
    all_different([$Q[I]+I : I in 1..N]),
    solve([ffd,split],Q).

% time1b/1 is a function that returns the time (ms)
time1b(Goal) = T =>
  statistics(runtime, _),
  call(Goal),
  statistics(runtime, [_,T]).


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program strTokenize64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ NBPOSTESECLAT,          20

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessFinal:         .asciz "Words are : \n"

szString:            .asciz "Hello,How,Are,You,Today"
szMessError:         .asciz "Error tokenize !!\n"
szCarriageReturn:    .asciz "\n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:
    ldr x0,qAdrszString                           // string address
    mov x1,','                                    // separator
    bl stTokenize
    cmp x0,-1                                     // error ?
    beq 99f
    mov x2,x0                                     // table address
    ldr x0,qAdrszMessFinal                        // display message
    bl affichageMess
    ldr x4,[x2]                                   // number of areas
    add x2,x2,8                                   // first area
    mov x3,0                                      // loop counter
    mov x0,x2
1:                                                // display loop
    ldr x0,[x2,x3, lsl 3]                         // address area
    bl affichageMess
    ldr x0,qAdrszCarriageReturn                   // display carriage return
    bl affichageMess
    add x3,x3,1                                  // counter + 1
    cmp x3,x4                                     // end ?
    blt 1b                                        // no -> loop

    b 100f
99:                                               // display error message
    ldr x0,qAdrszMessError
    bl affichageMess

100:                                              // standard end of the program
    mov x0,0                                       // return code
    mov x8,EXIT                                   // request to exit program
    svc 0                                         // perform the system call
qAdrszString:             .quad szString
//qAdrszFinalString:        .quad szFinalString
qAdrszMessFinal:          .quad szMessFinal
qAdrszMessError:          .quad szMessError
qAdrszCarriageReturn:     .quad szCarriageReturn

/*******************************************************************/
/* Separate string by separator into an array                     */
/* areas are store on the heap Linux                               */
/*******************************************************************/
/* x0 contains string address */
/* x1 contains separator character (, or . or : )    */
/* x0 returns table address with first item = number areas */
/* and other items contains pointer of each string     */
stTokenize:
    stp x1,lr,[sp,-16]!           // save  registers
    mov x16,x0
    mov x9,x1                     // save separator
    mov x14,0
1:                                // compute length string for place reservation on the heap
    ldrb w12,[x0,x14]
    cbz x12, 2f
    add x14,x14,1
    b 1b
2:
    ldr x12,qTailleTable
    add x15,x12,x14
    and x15,x15,0xFFFFFFFFFFFFFFF0
    add x15,x15,16                 // align word on the heap
                                  // place reservation on the heap
    mov x0,0                      // heap address
    mov x8,BRK                    // call system linux 'brk'
    svc 0                         // call system
    cmp x0,-1                     // error call system
    beq 100f
    mov x14,x0                    // save address  heap begin = begin array
    add x0,x0,x15                 // reserve x15 byte on the heap
    mov x8,BRK                    // call system linux 'brk'
    svc 0
    cmp x0,-1
    beq 100f
                                  // string copy on the heap
    add x13,x14,x12               // behind the array
    mov x0,x16
    mov x1,x13
3:                                // loop copy string
    ldrb w12,[x0],1               // read one byte and increment pointer one byte
    strb w12,[x1],1               // store one byte and increment pointer one byte
    cbnz x12,3b                   // end of string ? no -> loop

    mov x0,#0
    str x0,[x14]
    str x13,[x14,8]
    mov x12,#1                     // areas counter
4:                                // loop load string character
    ldrb w0,[x13]
    cbz x0,5f                     // end string
    cmp x0,x9                     // separator ?
    cinc x13,x13,ne               // no -> next location
    bne 4b                        // and loop
    strb wzr,[x13]                // store zero final of string
    add x13,x13,1                 // next character
    add x12,x12,1                 // areas counter + 1
    str x13,[x14,x12, lsl #3]     // store address area in the table at index x2
    b 4b                          // and loop

5:
    str x12,[x14]                 // store number areas
    mov x0,x14                    // returns array address
100:
    ldp x1,lr,[sp],16             // restaur  2 registers
    ret                           // return to address lr x30
qTailleTable:      .quad 8 * NBPOSTESECLAT

/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


(defun split-at (xs delim)
   (if (or (endp xs) (eql (first xs) delim))
       (mv nil (rest xs))
       (mv-let (before after)
               (split-at (rest xs) delim)
          (mv (cons (first xs) before) after))))

(defun split (xs delim)
   (if (endp xs)
       nil
       (mv-let (before after)
               (split-at xs delim)
          (cons before (split after delim)))))

(defun css->strs (css)
   (if (endp css)
       nil
       (cons (coerce (first css) 'string)
             (css->strs (rest css)))))

(defun split-str (str delim)
   (css->strs (split (coerce str 'list) delim)))

(defun print-with (strs delim)
   (if (endp strs)
       (cw "~%")
       (progn$ (cw (first strs))
               (cw (coerce (list delim) 'string))
               (print-with (rest strs) delim))))


data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
    override fun toString() = "$v"
}

fun preOrder(n: Node?) {
    n?.let {
        print("$n ")
        preOrder(n.left)
        preOrder(n.right)
    }
}

fun inorder(n: Node?) {
    n?.let {
        inorder(n.left)
        print("$n ")
        inorder(n.right)
    }
}

fun postOrder(n: Node?) {
    n?.let {
        postOrder(n.left)
        postOrder(n.right)
        print("$n ")
    }
}

fun levelOrder(n: Node?) {
    n?.let {
        val queue = mutableListOf(n)
        while (queue.isNotEmpty()) {
            val node = queue.removeAt(0)
            print("$node ")
            node.left?.let { queue.add(it) }
            node.right?.let { queue.add(it) }
        }
    }
}

inline fun exec(name: String, n: Node?, f: (Node?) -> Unit) {
    print(name)
    f(n)
    println()
}

fun main(args: Array<String>) {
    val nodes = Array(10) { Node(it) }

    nodes[1].left = nodes[2]
    nodes[1].right = nodes[3]

    nodes[2].left = nodes[4]
    nodes[2].right = nodes[5]

    nodes[4].left = nodes[7]

    nodes[3].left = nodes[6]

    nodes[6].left = nodes[8]
    nodes[6].right = nodes[9]

    exec("   preOrder: ", nodes[1], ::preOrder)
    exec("    inorder: ", nodes[1], ::inorder)
    exec("  postOrder: ", nodes[1], ::postOrder)
    exec("level-order: ", nodes[1], ::levelOrder)
}


using System;
using System.Text;
using System.Collections.Generic;

public class TokenizeAStringWithEscaping
{
    public static void Main() {
        string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";
        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {
            Console.WriteLine(": " + token); //Adding a : so we can see empty lines
        }
    }
}

public static class Extensions
{
    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {
        if (input == null) yield break;
        var buffer = new StringBuilder();
        bool escaping = false;
        foreach (char c in input) {
            if (escaping) {
                buffer.Append(c);
                escaping = false;
            } else if (c == escape) {
                escaping = true;
            } else if (c == separator) {
                yield return buffer.Flush();
            } else {
                buffer.Append(c);
            }
        }
        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();
    }

    public static string Flush(this StringBuilder stringBuilder) {
        string result = stringBuilder.ToString();
        stringBuilder.Clear();
        return result;
    }
}


#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using namespace std;

vector<string> tokenize(const string& input, char seperator, char escape) {
    vector<string> output;
    string token;

    bool inEsc = false;
    for (char ch : input) {
        if (inEsc) {
            inEsc = false;
        } else if (ch == escape) {
            inEsc = true;
            continue;
        } else if (ch == seperator) {
            output.push_back(token);
            token = "";
            continue;
        }
        token += ch;
    }
    if (inEsc)
        throw new invalid_argument("Invalid terminal escape");

    output.push_back(token);
    return output;
}

int main() {
    string sample = "one^|uno||three^^^^|four^^^|^cuatro|";

    cout << sample << endl;
    cout << '[';
    for (auto t : tokenize(sample, '|', '^')) {
        cout << '"' << t << "\", ";
    }
    cout << ']' << endl;

    return 0;
}


class topological
	dim dictDependencies
	dim dictReported
	dim depth

	sub class_initialize
		set dictDependencies = createobject("Scripting.Dictionary")
		set dictReported = createobject("Scripting.Dictionary")
		depth = 0
	end sub

	sub reset
		dictReported.removeall
	end sub

	property let dependencies( s )
		'assuming token tab token-list newline
		dim i, j ,k
		dim aList
		dim dep
		dim a1
		aList = Split( s, vbNewLine )
		'~ remove empty lines at end
		do while aList( UBound( aList ) ) = vbnullstring
			redim preserve aList( UBound( aList ) - 1 )
		loop

		for i = lbound( aList ) to ubound( aList )
			aList( i ) = Split( aList( i ), vbTab, 2 )
			a1 = Split( aList( i )( 1 ), " " )
			k = 0
			for j = lbound( a1) to ubound(a1)
				if a1(j) <> aList(i)(0) then
					a1(k) = a1(j)
					k = k + 1
				end if
			next
			redim preserve a1(k-1)
			aList(i)(1) = a1
		next
		for i = lbound( aList ) to ubound( aList )
			dep = aList(i)(0)
			if not dictDependencies.Exists( dep ) then
				dictDependencies.add dep, aList(i)(1)
			end if
		next

	end property

	sub resolve( s )
		dim i
		dim deps
		'~ wscript.echo string(depth,"!"),s
		depth = depth + 1
		if dictDependencies.Exists(s) then
			deps = dictDependencies(s)
			for i = lbound(deps) to ubound(deps)
				resolve deps(i)
			next
		end if
		if not seen(s) then
			wscript.echo s
			see s
		end if
		depth = depth - 1
	end sub

	function seen( key )
		seen = dictReported.Exists( key )
	end function

	sub see( key )
		dictReported.add key, ""
	end sub

	property get keys
		keys = dictDependencies.keys
	end property
end class


void get_some_primes()
{
    int i;
    while(i < 10000)
        i = i->next_prime();
}

void main()
{
    float time_wasted = gauge( get_some_primes() );
    write("Wasted %f CPU seconds calculating primes\n", time_wasted);
}


declare (start_time, finish_time) float (18);

start_time = secs();

do i = 1 to 10000000;
   /* something to be repeated goes here. */
end;
finish_time = secs();

put skip edit ('elapsed time=', finish_time - start_time, ' seconds')
   (A, F(10,3), A);
   /* gives the result to thousandths of a second. */

/* Note: using the SECS function takes into account the clock */
/* going past midnight. */


function fun($n){
    $res = 0
    if($n -gt 0) {
        1..$n | foreach{
            $a, $b = $_, ($n+$_)
            $res += $a + $b
        }

    }
    $res
}
"$((Measure-Command {fun 10000}).TotalSeconds) Seconds"


Procedure Foo(Limit)
  Protected i, palindromic, String$
  For i=0 To Limit
    String$=Str(i)
    If String$=ReverseString(String$)
      palindromic+1
    EndIf
  Next
  ProcedureReturn palindromic
EndProcedure

If OpenConsole()
  Define Start, Stop, cnt
  PrintN("Starting timing of a calculation,")
  PrintN("for this we test how many of 0-1000000 are palindromic.")
  Start=ElapsedMilliseconds()
  cnt=Foo(1000000)
  Stop=ElapsedMilliseconds()
  PrintN("The function need "+Str(stop-Start)+" msec,")
  PrintN("and "+Str(cnt)+" are palindromic.")
  Print("Press ENTER to exit."): Input()
EndIf


var hello:String = "Hello,How,Are,You,Today";
var tokens:Array = hello.split(",");
trace(tokens.join("."));

// Or as a one-liner
trace("Hello,How,Are,You,Today".split(",").join("."));


with Ada.Text_IO, Ada.Containers.Indefinite_Vectors, Ada.Strings.Fixed, Ada.Strings.Maps;
use Ada.Text_IO, Ada.Containers, Ada.Strings, Ada.Strings.Fixed, Ada.Strings.Maps;

procedure Tokenize is
   package String_Vectors is new Indefinite_Vectors (Positive, String);
   use String_Vectors;
   Input  : String   := "Hello,How,Are,You,Today";
   Start  : Positive := Input'First;
   Finish : Natural  := 0;
   Output : Vector   := Empty_Vector;
begin
   while Start <= Input'Last loop
      Find_Token (Input, To_Set (','), Start, Outside, Start, Finish);
      exit when Start > Finish;
      Output.Append (Input (Start .. Finish));
      Start := Finish + 1;
   end loop;
   for S of Output loop
      Put (S & ".");
   end loop;
end Tokenize;


- {W.equal? word1 word2}   returns true or false
- {S.replace rex by exp1 in exp2}
                           replaces a regular expression by some expression in another one
- {S.sort comp words}      sorts the sequence of words according to comp
- {A.new words}            creates a new array from the sequence of words
- {A.get index array}      gets the value of array at index


tokenize = iter (sep, esc: char, s: string) yields (string)
    escape: bool := false
    part: array[char] := array[char]$[]
    for c: char in string$chars(s) do
        if escape then
            escape := false
            array[char]$addh(part,c)
        elseif c=esc then
            escape := true
        elseif c=sep then
            yield(string$ac2s(part))
            part := array[char]$[]
        else
            array[char]$addh(part,c)
        end
    end
    yield(string$ac2s(part))
end tokenize

start_up = proc ()
    po: stream := stream$primary_output()
    testcase: string := "one^|uno||three^^^^|four^^^|^quatro|"

    for part: string in tokenize('|', '^', testcase) do
        stream$putl(po, "\"" || part || "\"")
    end
end start_up


       >>SOURCE FORMAT FREE
identification division.
program-id. 'tokenizewithescaping'.
environment division.
configuration section.
repository.
    function all intrinsic.
data division.
working-storage section.

01 escape-char pic x value '^'.
01 separator-char pic x value '|'.
01 reference-string pic x(64) value
   'one^|uno||three^^^^|four^^^|^cuatro|'.

01 input-string pic x(64).
01 c pic 99.
01 escaped pic x.

01 t pic 99.
01 t-max pic 99.
01 t-lim pic 99 value 32.
01 token-entry occurs 32.
   03  token-len pic 99.
   03  token pic x(16).

01 l pic 99.
01 l-lim pic 99 value 16.

01 error-found pic x.

procedure division.
start-tokenize-with-escaping.

    move reference-string to input-string
    perform tokenize

    move 'token' to input-string
    perform tokenize

    move '^^^^^^^^' to input-string
    perform tokenize

    move '||||||||' to input-string
    perform tokenize

    move all 'token' to input-string
    perform tokenize

    move all 't|' to input-string
    perform tokenize

    move spaces to input-string
    perform tokenize

    display space

    stop run
    .
tokenize.
    display space
    display 'string:'
    display input-string

    move 'N' to escaped error-found
    move 1 to t-max
    initialize token-entry(t-max)
    move 0 to l

    perform varying c from 1 by 1 until
    c > length(input-string)
    or input-string(c:) = spaces

        evaluate escaped also input-string(c:1)
        when 'N' also escape-char
            move 'Y' to escaped
        when 'N' also separator-char
            perform increment-t-max
            if error-found = 'Y'
                exit paragraph
            end-if
        when 'N' also any
            perform move-c
            if error-found = 'Y'
                exit paragraph
            end-if
        when 'Y' also any
            perform move-c
            if error-found = 'Y'
                exit paragraph
            end-if
            move 'N' to escaped
        end-evaluate

    end-perform
    if l > 0
        move l to token-len(t-max)
    end-if

    if c = 1
        display 'no tokens'
    else
        display 'tokens:'
        perform varying t from 1 by 1 until t > t-max
            if token-len(t) > 0
                display t ': ' token-len(t) space token(t)
            else
                display t ': ' token-len(t)
            end-if
        end-perform
    end-if
    .
increment-t-max.
    if t-max >= t-lim
        display 'error: at ' c ' number of tokens exceeds ' t-lim
        move 'Y' to error-found
    else
        move l to token-len(t-max)
        add 1 to t-max
        initialize token-entry(t-max)
        move 0 to l
        move 'N' to error-found
    end-if
    .
move-c.
    if l >= l-lim
        display 'error: at ' c ' token length exceeds ' l-lim
        move 'Y' to error-found
    else
        add 1 to l
        move input-string(c:1) to token(t-max)(l:1)
        move 'N' to error-found
    end-if
    .
end program 'tokenizewithescaping'.


' Adapted from:
' http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html
' added/changed:
' - conversion to VB.Net (.Net 2 framework)
' - added Rosetta Code dependency format parsing
' - check & removal of self-dependencies before sorting
Module Program
	Sub Main()
		Dim Fields As New List(Of Field)()
		' You can also add Dependson using code like:
		' .DependsOn = New String() {"ieee", "dw01", "dware"} _

		fields.Add(New Field() With { _
			.Name = "des_system_lib", _
			.DependsOn = Split("std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "dw01", _
			.DependsOn = Split("ieee dw01 dware gtech", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "dw02", _
			.DependsOn = Split("ieee dw02 dware", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "dw03", _
			.DependsOn = Split("std synopsys dware dw03 dw02 dw01 ieee gtech", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "dw04", _
			.DependsOn = Split("dw04 ieee dw01 dware gtech", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "dw05", _
			.DependsOn = Split("dw05 ieee dware", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "dw06", _
			.DependsOn = Split("dw06 ieee dware", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "dw07", _
			.DependsOn = Split("ieee dware", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "dware", _
			.DependsOn = Split("ieee dware", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "gtech", _
			.DependsOn = Split("ieee gtech", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "ramlib", _
			.DependsOn = Split("std ieee", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "std_cell_lib", _
			.DependsOn = Split("ieee std_cell_lib", " ") _
		})
		fields.Add(New Field() With { _
			.Name = "synopsys" _
		})
		Console.WriteLine("Input:")
		For Each ThisField As field In fields
			Console.WriteLine(ThisField.Name)
			If ThisField.DependsOn IsNot Nothing Then
				For Each item As String In ThisField.DependsOn
					Console.WriteLine(" -{0}", item)
				Next
			End If
		Next

		Console.WriteLine(vbLf & "...Sorting..." & vbLf)

		Dim sortOrder As Integer() = getTopologicalSortOrder(fields)

		For i As Integer = 0 To sortOrder.Length - 1
			Dim field = fields(sortOrder(i))
			Console.WriteLine(field.Name)
			' Write up dependencies, too:
			'If field.DependsOn IsNot Nothing Then
			'	For Each item As String In field.DependsOn
			'		Console.WriteLine(" -{0}", item)
			'	Next
			'End If
		Next
		Console.Write("Press any key to continue . . . ")
		Console.ReadKey(True)
	End Sub

	Private Sub CheckDependencies (ByRef Fields As List(Of Field))
		' Make sure all objects we depend on are part of the field list
		' themselves, as there may be dependencies that are not specified as fields themselves.
		' Remove dependencies on fields themselves.Y
		Dim AField As Field, ADependency As String

		For i As Integer = Fields.Count - 1 To 0 Step -1
			AField=fields(i)
			If AField.DependsOn IsNot Nothing  then
				For j As Integer = 0 To Ubound(AField.DependsOn)
					ADependency = Afield.DependsOn(j)
					' We ignore fields that depends on themselves:
					If AField.Name <> ADependency then
						If ListContainsVertex(fields, ADependency) = False Then
							' Add the dependent object to the field list, as it
							' needs to be there, without any dependencies
							Fields.Add(New Field() With { _
								.Name = ADependency _
							})
						End If
					End If
				Next j
			End If
		Next i
	End Sub

	Private Sub RemoveSelfDependencies (ByRef Fields As List(Of Field))
		' Make sure our fields don't depend on themselves.
		' If they do, remove the dependency.
		Dim InitialUbound as Integer
		For Each AField As Field In Fields
			If AField.DependsOn IsNot Nothing Then
				InitialUbound = Ubound(AField.DependsOn)
				For i As Integer = InitialUbound to 0 Step - 1
					If Afield.DependsOn(i) = Afield.Name Then
						' This field depends on itself, so remove
						For j as Integer = i To UBound(AField.DependsOn)-1
							Afield.DependsOn(j)=Afield.DependsOn(j+1)
						Next
						ReDim Preserve Afield.DependsOn(UBound(Afield.DependsOn)-1)
					End If
				Next
			End If
		Next
	End Sub

	Private Function ListContainsVertex(Fields As List(Of Field), VertexName As String) As Boolean
	' Check to see if the list of Fields already contains a vertext called VertexName
	Dim Found As Boolean = False
		For i As Integer = 0 To fields.Count - 1
			If Fields(i).Name = VertexName Then
				Found = True
				Exit For
			End If
		Next
		Return Found
	End Function

	Private Function getTopologicalSortOrder(ByRef Fields As List(Of Field)) As Integer()
		' Gets sort order. Will also add required dependencies to
		' Fields.

		' Make sure we don't have dependencies on ourselves.
		' We'll just get rid of them.
		RemoveSelfDependencies(Fields)

		'First check depencies, add them to Fields if required:
		CheckDependencies(Fields)
		' Now we have the correct Fields list, so we can proceed:
		Dim g As New TopologicalSorter(fields.Count)
		Dim _indexes As New Dictionary(Of String, Integer)(fields.count)

		'add vertex names to our lookup dictionaey
		For i As Integer = 0 To fields.Count - 1
			_indexes(fields(i).Name.ToLower()) = g.AddVertex(i)
		Next

		'add edges
		For i As Integer = 0 To fields.Count - 1
			If fields(i).DependsOn IsNot Nothing Then
				For j As Integer = 0 To fields(i).DependsOn.Length - 1
					g.AddEdge(i, _indexes(fields(i).DependsOn(j).ToLower()))
				Next
			End If
		Next

		Dim result As Integer() = g.Sort()
		Return result
	End Function

	Private Class Field
		Public Property Name() As String
			Get
				Return m_Name
			End Get
			Set
				m_Name = Value
			End Set
		End Property
		Private m_Name As String
		Public Property DependsOn() As String()
			Get
				Return m_DependsOn
			End Get
			Set
				m_DependsOn = Value
			End Set
		End Property
		Private m_DependsOn As String()
	End Class
End Module
Class TopologicalSorter
	''source adapted from:
	''http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html
	''which was adapted from:
	''http://www.java2s.com/Code/Java/Collections-Data-Structure/Topologicalsorting.htm
	#Region "- Private Members -"

	Private ReadOnly _vertices As Integer()
	' list of vertices
	Private ReadOnly _matrix As Integer(,)
	' adjacency matrix
	Private _numVerts As Integer
	' current number of vertices
	Private ReadOnly _sortedArray As Integer()
	' Sorted vertex labels

	#End Region

	#Region "- CTors -"

	Public Sub New(size As Integer)
		_vertices = New Integer(size - 1) {}
		_matrix = New Integer(size - 1, size - 1) {}
		_numVerts = 0
		For i As Integer = 0 To size - 1
			For j As Integer = 0 To size - 1
				_matrix(i, j) = 0
			Next
		Next
			' sorted vert labels
		_sortedArray = New Integer(size - 1) {}
	End Sub

	#End Region

	#Region "- Public Methods -"

	Public Function AddVertex(vertex As Integer) As Integer
		_vertices(System.Threading.Interlocked.Increment(_numVerts)-1) = vertex
		Return _numVerts - 1
	End Function

	Public Sub AddEdge(start As Integer, [end] As Integer)
		_matrix(start, [end]) = 1
	End Sub

	Public Function Sort() As Integer()
	' Topological sort
		While _numVerts > 0
			' while vertices remain,
			' get a vertex with no successors, or -1
			Dim currentVertex As Integer = noSuccessors()
			If currentVertex = -1 Then
				' must be a cycle
				Throw New Exception("Graph has cycles")
			End If

			' insert vertex label in sorted array (start at end)
			_sortedArray(_numVerts - 1) = _vertices(currentVertex)

				' delete vertex
			deleteVertex(currentVertex)
		End While

		' vertices all gone; return sortedArray
		Return _sortedArray
	End Function

	#End Region

	#Region "- Private Helper Methods -"

	' returns vert with no successors (or -1 if no such verts)
	Private Function noSuccessors() As Integer
		For row As Integer = 0 To _numVerts - 1
			Dim isEdge As Boolean = False
			' edge from row to column in adjMat
			For col As Integer = 0 To _numVerts - 1
				If _matrix(row, col) > 0 Then
					' if edge to another,
					isEdge = True
						' this vertex has a successor try another
					Exit For
				End If
			Next
			If Not isEdge Then
				' if no edges, has no successors
				Return row
			End If
		Next
		Return -1
		' no
	End Function

	Private Sub deleteVertex(delVert As Integer)
		' if not last vertex, delete from vertexList
		If delVert <> _numVerts - 1 Then
			For j As Integer = delVert To _numVerts - 2
				_vertices(j) = _vertices(j + 1)
			Next

			For row As Integer = delVert To _numVerts - 2
				moveRowUp(row, _numVerts)
			Next

			For col As Integer = delVert To _numVerts - 2
				moveColLeft(col, _numVerts - 1)
			Next
		End If
		_numVerts -= 1
		' one less vertex
	End Sub

	Private Sub moveRowUp(row As Integer, length As Integer)
		For col As Integer = 0 To length - 1
			_matrix(row, col) = _matrix(row + 1, col)
		Next
	End Sub

	Private Sub moveColLeft(col As Integer, length As Integer)
		For row As Integer = 0 To length - 1
			_matrix(row, col) = _matrix(row, col + 1)
		Next
	End Sub

	#End Region
End Class


import sys, timeit
def usec(function, arguments):
    modname, funcname = __name__, function.__name__
    timer = timeit.Timer(stmt='%(funcname)s(*args)' % vars(),
                         setup='from %(modname)s import %(funcname)s; args=%(arguments)r' % vars())
    try:
        t, N = 0, 1
        while t < 0.2:
            t = min(timer.repeat(repeat=3, number=N))
            N *= 10
        microseconds = round(10000000 * t / N, 1) # per loop
        return microseconds
    except:
        timer.print_exc(file=sys.stderr)
        raise

from math import pow
def nothing(): pass
def identity(x): return x


# A task
foo <- function()
{
   for(i in 1:10)
   {
      mat <- matrix(rnorm(1e6), nrow=1e3)
      mat^-0.5
   }
}
# Time the task
timer <- system.time(foo())
# Extract the processing time
timer["user.self"]


#lang racket
(define (fact n) (if (zero? n) 1 (* n (fact (sub1 n)))))
(time (fact 5000))


my $start = now;
(^100000).pick(1000);
say now - $start;


define doId use $x
   $x dup * $x /

define doPower use $v, $p
   $v $p pow

define doSort
   group
      20000 each choose
   list sort reverse

define timeFunc use $fName
   time as $t1
   $fName "" prefer call
   time as $t2
   $fName $t2 $t1 -"%.4g secs for %s\n" print

"NULL" timeFunc
42 "doId" timeFunc
12 2 "doPower" timeFunc
"doSort" timeFunc


main:(

  OP +:=  = (REF FLEX[]STRING in out, STRING item)VOID:(
    [LWB in out: UPB in out+1]STRING new;
    new[LWB in out: UPB in out]:=in out;
    new[UPB new]:=item;
    in out := new
  );

  PROC string split = (REF STRING beetles, STRING substr)[]STRING:(
    """ Split beetles where substr is found """;
    FLEX[1:0]STRING out;
    INT start := 1, pos;
    WHILE string in string(substr, pos, beetles[start:]) DO
      out +:= STRING(beetles[start:start+pos-2]);
      start +:= pos + UPB substr - 1
    OD;
    IF start > LWB beetles THEN
      out +:= STRING(beetles[start:])
    FI;
    out
  );

  PROC char split = (REF STRING beetles, STRING chars)[]STRING: (
    """ Split beetles where character is found in chars """;
    FLEX[1:0]STRING out;
    FILE beetlef;
    associate(beetlef, beetles); # associate a FILE handle with a STRING   #
    make term(beetlef, chars);   # make term: assign CSV string terminator #

    PROC raise logical file end = (REF FILE f)BOOL: except logical file end;
    on logical file end(beetlef, raise logical file end);

    STRING solo;
    DO
      getf(beetlef, ($g$, solo));
      out+:=solo;
      getf(beetlef, ($x$)) # skip CHAR separator #
    OD;
    except logical file end:
      SKIP;
    out
  );

  STRING beetles := "John Lennon, Paul McCartney, George Harrison, Ringo Starr";

  printf(($g"."$, string split(beetles, ", "),$l$));
  printf(($g"."$, char   split(beetles, ", "),$l$))
)


-- parent script "BinaryTreeNode"

property _val, _left, _right

on new (me, val)
  me._val = val
  return me
end

on getValue (me)
  return me._val
end

on setLeft (me, node)
  me._left = node
end

on setRight (me, node)
  me._right = node
end

on getLeft (me)
  return me._left
end

on getRight (me)
  return me._right
end


(defun split (input separator escape)
  (flet ((make-string-buffer ()
           (make-array 0 :element-type 'character :adjustable t :fill-pointer t)))
    (loop with token = (make-string-buffer)
          with result = nil
          with to-be-escaped = nil
          for ch across input
          do (cond (to-be-escaped
                    (vector-push-extend ch token)
                    (setf to-be-escaped nil))
                   ((char= ch escape)
                    (setf to-be-escaped t))
                   ((char= ch separator)
                    (push token result)
                    (setf token (make-string-buffer)))
                   (t
                    (vector-push-extend ch token)))
          finally (push token result)
                  (return (nreverse result)))))

(defun main ()
  (dolist (token (split "one^|uno||three^^^^|four^^^|^cuatro|" #\| #\^))
    (format t "'~A'~%" token)))


import std.stdio;

void main() {
    string sample = "one^|uno||three^^^^|four^^^|^cuatro|";

    writeln(sample);
    writeln(tokenizeString(sample, '|', '^'));
}

auto tokenizeString(string source, char seperator, char escape) {
    import std.array : appender;
    import std.exception : enforce;

    auto output = appender!(string[]);
    auto token = appender!(char[]);

    bool inEsc;
    foreach(ch; source) {
        if (inEsc) {
            inEsc = false;
        } else if (ch == escape) {
            inEsc = true;
            continue;
        } else if (ch == seperator) {
            output.put(token.data.idup);
            token.clear();
            continue;
        }
        token.put(ch);
    }
    enforce(!inEsc, "Invalid terminal escape");

    output.put(token.data.idup);
    return output.data;
}


class Graph {
    construct new(s, edges) {
        _vertices = s.split(", ")
        var n = _vertices.count
        _adjacency = List.filled(n, null)
        for (i in 0...n) _adjacency[i] = List.filled(n, false)
        for (edge in edges) _adjacency[edge[0]][edge[1]] = true
    }

    hasDependency(r, todo) {
        for (c in todo) if (_adjacency[r][c]) return true
        return false
    }

    topoSort() {
        var res = []
        var todo = List.filled(_vertices.count, 0)
        for (i in 0...todo.count) todo[i] = i
        while (!todo.isEmpty) {
            var outer = false
            var i = 0
            for (r in todo) {
                if (!hasDependency(r, todo)) {
                    todo.removeAt(i)
                    res.add(_vertices[r])
                    outer = true
                    break
                }
                i = i + 1
            }
            if (!outer) {
                System.print("Graph has cycles")
                return ""
            }
        }
        return res
    }
}

var s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
        "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"

var deps = [
    [2, 0], [2, 14], [2, 13], [2, 4], [2, 3], [2, 12], [2, 1],
    [3, 1], [3, 10], [3, 11],
    [4, 1], [4, 10],
    [5, 0], [5, 14], [5, 10], [5, 4], [5, 3], [5, 1], [5, 11],
    [6, 1], [6, 3], [6, 10], [6, 11],
    [7, 1], [7, 10],
    [8, 1], [8, 10],
    [9, 1], [9, 10],
    [10, 1],
    [11, 1],
    [12, 0], [12, 1],
    [13, 1]
]

var g = Graph.new(s, deps)
System.print("Topologically sorted order:")
System.print(g.topoSort())
System.print()
// now insert [3, 6] at index 10 of deps
deps.insert(10, [3, 6])
var g2 = Graph.new(s, deps)
System.print("Following the addition of dw04 to the dependencies of dw01:")
System.print(g2.topoSort())


: .runtime ( a- ) time [ do time ] dip - "\n%d\n" puts ;

: test 20000 [ putn space ] iterd ;
&test .runtime


/*REXX program displays the elapsed time for a REXX function (or subroutine). */
arg reps .                             /*obtain an optional argument from C.L.*/
if reps==''  then reps=100000          /*Not specified?  No, then use default.*/
call time 'Reset'                      /*only the 1st character is examined.  */
junk = silly(reps)                     /*invoke the  SILLY  function (below). */
                                       /*───►   CALL SILLY REPS    also works.*/

             /*                          The    E   is for    elapsed    time.*/
             /*                                 │             ─               */
             /*                        ┌────◄───┘                             */
             /*                        │                                      */
             /*                        ↓                                      */
say 'function SILLY took' format(time("E"),,2)  'seconds for' reps "iterations."
             /*                             ↑                                 */
             /*                             │                                 */
             /*            ┌────────►───────┘                                 */
             /*            │                                                  */
             /* The above  2  for the  FORMAT  function displays the time with*/
             /* two decimal digits (rounded)  past the decimal point).  Using */
             /* a   0  (zero)    would round the  time  to whole seconds.     */
exit                                   /*stick a fork in it,  we're all done. */
/*────────────────────────────────────────────────────────────────────────────*/
silly: procedure               /*chew up some CPU time doing some silly stuff.*/
            do j=1  for arg(1) /*wash,  apply,  lather,  rinse,  repeat.  ··· */
            @.j=random() date() time() digits() fuzz() form() xrange() queued()
            end   /*j*/
 return j-1


beginTime = TimeList()[13]
for n = 1 to 10000000
    n = n + 1
next
endTime = TimeList()[13]
elapsedTime = endTime - beginTime
see "Elapsed time = " + elapsedTime + nl


require 'benchmark'

Benchmark.bm(8) do |x|
  x.report("nothing:")  {  }
  x.report("sum:")  { (1..1_000_000).inject(4) {|sum, x| sum + x} }
end


#include <hopper.h>

#proto splitdate(_DATETIME_)
#proto splitnumber(_N_)
#proto split(_S_,_T_)

main:

    s="this string will be separated into parts with space token separator"

    aS=0,let( aS :=_split(s," "))

    {","}toksep                     // set a new token separator
    {"String: ",s}
    {"\nArray:\n",aS},
    {"\nSize="}size(aS),println     // "size" return an array: {dims,#rows,#cols,#pages}

    {"\nOriginal number: ",-125.489922},println
    w=0,let(w:=_split number(-125.489922) )
    {"Integer part: "}[1]get(w)              // get first element from array "w"
    {"\nDecimal part: "}[2]get(w),println    // get second element from array "w"

    {"\nDate by DATENOW(TODAY) macro: "},print
    dt=0, let( dt :=_splitdate(datenow(TODAY);!puts))  // "!" keep first element from stack
    {"\nDate: "}[1]get(dt)
    {"\nTime: "}[2]get(dt),println

exit(0)

.locals
splitdate(_DATETIME_)
    _SEP_=0,gettoksep,mov(_SEP_)      // "gettoksep" return actual token separator
    {","}toksep,                      // set a new token separator
    _NEWARRAY_={}
    {1},$( _DATETIME_ ),
    {2},$( _DATETIME_ ),pushall(_NEWARRAY_)
    {_SEP_}toksep                     // restore ols token separator
   {_NEWARRAY_}
back

splitnumber(_X_)
   part_int=0,part_dec=0,
   {_X_},!trunc,mov(part_int),
   minus(part_int), !sign,mul
   xtostr,mov(part_dec), part_dec+=2, // "part_dec+=2", delete "0." from "part_dec"
   {part_dec}xtonum,mov(part_dec)
   _NEWARRAY_={},{part_int,part_dec},pushall(_NEWARRAY_)
   {_NEWARRAY_}
back

split(_S_,_T_)
    _NEWARRAY_={},_VAR1_=0,_SEP_=0,gettoksep,mov(_SEP_)
   {_T_}toksep,totaltoken(_S_),
   mov(_VAR1_),                      // for total tokens
   _VAR2_=1,                         // for real position of tokens into the string
   ___SPLIT_ITER:
       {_VAR2_}$( _S_ ),push(_NEWARRAY_)
       ++_VAR2_,--_VAR1_
       { _VAR1_ },jnz(___SPLIT_ITER) // jump to "___SPLIT_ITER" if "_VAR1_" is not zero.
   clear(_VAR2_),clear(_VAR1_)
   {_SEP_}toksep
   {_NEWARRAY_}
back


     '.',⍨¨ ','(≠⊆⊢)'abc,123,X'   ⍝ [1] Do the split: ','(≠⊆⊢)'abc,123,X'; [2] append the periods: '.',⍨¨
 abc.  123.  X.                   ⍝ 3 strings (char vectors), each with a period at the end.


on run
  intercalate(".", splitOn(",", "Hello,How,Are,You,Today"))
end run

-- splitOn :: String -> String -> [String]
on splitOn(strDelim, strMain)
  set {dlm, my text item delimiters} to {my text item delimiters, strDelim}
  set lstParts to text items of strMain
  set my text item delimiters to dlm
  return lstParts
end splitOn

-- intercalate :: String -> [String] -> String
on intercalate(strText, lstText)
  set {dlm, my text item delimiters} to {my text item delimiters, strText}
  set strJoined to lstText as text
  set my text item delimiters to dlm
  return strJoined
end intercalate


; nodes are [data left right], use "first" to get data

to node.left :node
  if empty? butfirst :node [output []]
  output first butfirst :node
end
to node.right :node
  if empty? butfirst :node [output []]
  if empty? butfirst butfirst :node [output []]
  output first butfirst butfirst :node
end
to max :a :b
  output ifelse :a > :b [:a] [:b]
end
to tree.depth :tree
  if empty? :tree [output 0]
  output 1 + max tree.depth node.left :tree  tree.depth node.right :tree
end

to pre.order :tree :action
  if empty? :tree [stop]
  invoke :action first :tree
  pre.order node.left :tree :action
  pre.order node.right :tree :action
end
to in.order :tree :action
  if empty? :tree [stop]
  in.order node.left :tree :action
  invoke :action first :tree
  in.order node.right :tree :action
end
to post.order :tree :action
  if empty? :tree [stop]
  post.order node.left :tree :action
  post.order node.right :tree :action
  invoke :action first :tree
end
to at.depth :n :tree :action
  if empty? :tree [stop]
  ifelse :n = 1 [invoke :action first :tree] [
    at.depth :n-1 node.left  :tree :action
    at.depth :n-1 node.right :tree :action
  ]
end
to level.order :tree :action
  for [i 1 [tree.depth :tree]] [at.depth :i :tree :action]
end

make "tree [1 [2 [4 [7]]
                 [5]]
              [3 [6 [8]
                    [9]]]]

  pre.order :tree [(type ? "| |)]  (print)
   in.order :tree [(type ? "| |)]  (print)
 post.order :tree [(type ? "| |)]  (print)
level.order :tree [(type ? "| |)]  (print)


func String.Tokenize(separator, escape) {
    var buffer = []
    var escaping = false
    for c in this {
        if escaping {
            buffer.Add(c)
            escaping = false
        } else if c == escape {
            escaping = true
        } else if c == separator {
            yield buffer.Flush();
        } else {
            buffer.Add(c);
        }
    }

    if buffer.Length() > 0 || this[this.Length() - 1] == separator {
        yield buffer.Flush()
    }
}

func Array.Flush() {
    var str = String.Concat(values: this)
    this.Clear()
    str
}

let testcase = "one^|uno||three^^^^|four^^^|^cuatro|";
for token in testcase.Tokenize(separator: '|', escape: '^') {
    print(": \(token)")
}


import extensions;
import extensions'routines;
import system'collections;
import system'routines;
import system'text;

extension op : String
{
    tokenize(separator,escape)
    {
        auto buffer := new TextBuilder();
        auto list := new ArrayList();

        bool escaping := false;
        self.forEach:(ch)
        {
            if (escaping)
            {
                buffer.write:ch;
                escaping := false
            }
            else if (ch == escape)
            {
                escaping := true
            }
            else if (ch == separator)
            {
                list.append(buffer.Value);
                buffer.clear()
            }
            else
            {
                buffer.write:ch
            }
        };

        ^ list
    }
}

const string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";

public program()
{
    testcase.tokenize("|", "^").forEach:printingLn
}


open System
open System.Text.RegularExpressions

(*
    .NET regexes have unlimited look-behind, so we can look for separators
    which are preceeded by an even number of (or no) escape characters
*)
let split esc sep s =
    Regex.Split (
        s,
        String.Format("(?<=(?:\b|[^{0}])(?:{0}{0})*){1}", Regex.Escape(esc), Regex.Escape(sep))
        )

let unescape esc s =
    Regex.Replace(
        s,
        Regex.Escape(esc) + "(.)",
        "$1"
        )

[<EntryPoint>]
let main argv =
    let (esc, sep) = ("^", "|")
    "one^|uno||three^^^^|four^^^|^cuatro|"
    |> split esc sep
    |> Seq.map (unescape esc)
    |> Seq.iter (fun s -> printfn "'%s'" s)
    0


USING: accessors kernel lists literals namespaces
parser-combinators prettyprint sequences strings ;

SYMBOLS: esc sep ;

: set-chars ( m n -- ) [ sep set ] [ esc set ] bi* ;
: escape ( -- parser ) esc get 1token ;
: escaped ( -- parser ) escape any-char-parser &> ;
: separator ( -- parser ) sep get 1token ;

: character ( -- parser )
    ${ esc get sep get } [ member? not ] curry satisfy ;

: my-token ( -- parser ) escaped character <|> <*> ;

: token-list ( -- parser )
    my-token separator list-of [ [ >string ] map ] <@ ;

: tokenize ( str sep-char esc-char -- seq )
    set-chars token-list parse car parsed>> ;

"one^|uno||three^^^^|four^^^|^cuatro|"
CHAR: | CHAR: ^ tokenize .


fcn topoSort(data){ // data is L( L(root,L(leaves)),...)
   allDs:=data.pump(List,fcn(rds){ T(Void.Write,Void.Write,rds[1]) }).copy();
   roots:=Dictionary(data); // dictionary of root:leaves
   L:=List();
   S:=data.pump(List,'wrap([(r,_)]){ if(allDs.holds(r)) Void.Skip else r }).copy();
   while(S){        //while S is non-empty do
      (n:=S.pop()) : L.append(_); //remove a node n from S, add n to tail of L
      foreach m in (ds:=roots.find(n,List)){ //node m with an edge e from n to m
	 allDs.del(allDs.index(m));
	 if (Void==allDs.find(m)) S.append(m); //m has no other incoming edges
      } roots.del(n);  // remove edge e from the graph
   }
   if(roots) throw(Exception.ValueError("Cycle: "+roots.keys));
   L
}


// 20210224 Rust programming solution

use rand::Rng;
use std::time::{Instant};

fn custom_function() {

   let mut i = 0;
   let mut rng = rand::thread_rng();
   let n1: f32 = rng.gen();

   while i < ( 1000000 + 1000000 * ( n1.log10() as i32 ) ) {
      i = i + 1;
   }
}

fn main() {

   let start = Instant::now();
   custom_function();
   let duration = start.elapsed();

   println!("Time elapsed in the custom_function() is : {:?}", duration);
}


def time(f: => Unit)={
	val s = System.currentTimeMillis
	f
	System.currentTimeMillis - s
}


$ include "seed7_05.s7i";
  include "time.s7i";
  include "duration.s7i";

const func integer: identity (in integer: x) is
  return x;

const func integer: sum (in integer: num) is func
  result
    var integer: result is 0;
  local
    var integer: number is 0;
  begin
    result := num;
    for number range 1 to 1000000 do
      result +:= number;
    end for;
  end func;

const func duration: timeIt (ref func integer: aFunction) is func
  result
    var duration: result is duration.value;
  local
    var time: before is time.value;
  begin
    before := time(NOW);
    ignore(aFunction);
    result := time(NOW) - before;
  end func;

const proc: main is func
  begin
    writeln("Identity(4) takes " <& timeIt(identity(4)));
    writeln("Sum(4)      takes " <& timeIt(sum(4)));
  end func;


var benchmark = frequire('Benchmark')

func fac_rec(n) {
    n == 0 ? 1 : (n * __FUNC__(n - 1))
}

func fac_iter(n) {
    var prod = 1
    n.times { |i|
        prod *= i
    }
    prod
}

var result = benchmark.timethese(-3, Hash(
    'fac_rec'  => { fac_rec(20)  },
    'fac_iter' => { fac_iter(20) },
))

benchmark.cmpthese(result)


/* ARM assembly Raspberry PI  */
/*  program strTokenize.s   */

/* Constantes    */
.equ STDOUT, 1                          @ Linux output console
.equ EXIT,   1                           @ Linux syscall
.equ WRITE,  4                           @ Linux syscall

.equ NBPOSTESECLAT,          20

/* Initialized data */
.data
szMessFinal:   .asciz "Words are : \n"

szString:            .asciz "Hello,How,Are,You,Today"
szMessError:         .asciz "Error tokenize !!\n"
szCarriageReturn:   .asciz "\n"

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:
    ldr r0,iAdrszString                           @ string address
    mov r1,#','                                   @ separator
    bl stTokenize
    cmp r0,#-1                                    @ error ?
    beq 99f
    mov r2,r0                                     @ table address
    ldr r0,iAdrszMessFinal                        @ display message
    bl affichageMess
    ldr r4,[r2]                                   @ number of areas
    add r2,#4                                     @ first area
    mov r3,#0                                     @ loop counter
1:                                                @ display loop
    ldr r0,[r2,r3, lsl #2]                        @ address area
    bl affichageMess
    ldr r0,iAdrszCarriageReturn                   @ display carriage return
    bl affichageMess
    add r3,#1                                     @ counter + 1
    cmp r3,r4                                     @ end ?
    blt 1b                                        @ no -> loop

    b 100f
99:                                               @ display error message
    ldr r0,iAdrszMessError
    bl affichageMess

100:                                              @ standard end of the program
    mov r0, #0                                    @ return code
    mov r7, #EXIT                                 @ request to exit program
    svc 0                                         @ perform the system call
iAdrszString:             .int szString
iAdrszFinalString:       .int szFinalString
iAdrszMessFinal:          .int szMessFinal
iAdrszMessError:          .int szMessError
iAdrszCarriageReturn:    .int szCarriageReturn
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                       @ save  registers
    mov r2,#0                                   @ counter length */
1:                                              @ loop length calculation
    ldrb r1,[r0,r2]                             @ read octet start position + index
    cmp r1,#0                                   @ if 0 its over
    addne r2,r2,#1                              @ else add 1 in the length
    bne 1b                                      @ and loop
                                                @ so here r2 contains the length of the message
    mov r1,r0                                   @ address message in r1
    mov r0,#STDOUT                              @ code to write to the standard output Linux
    mov r7, #WRITE                              @ code call system "write"
    svc #0                                      @ call systeme
    pop {r0,r1,r2,r7,lr}                        @ restaur des  2 registres
    bx lr                                       @ return
/*******************************************************************/
/* Separate string by separator into an array                     */
/* areas are store on the heap Linux                               */
/*******************************************************************/
/* r0 contains string address */
/* r1 contains separator character (, or . or : )    */
/* r0 returns table address with first item = number areas */
/* and other items contains pointer of each string     */
stTokenize:
    push {r1-r8,lr}                                 @ save des registres
    mov r6,r0
    mov r8,r1                                       @ save separator
    bl strLength                                    @ length string for place reservation on the heap
    mov r4,r0
    ldr r5,iTailleTable
    add r5,r0
    and r5,#0xFFFFFFFC
    add r5,#4                                       @ align word on the heap
                                                    @ place reservation on the heap
    mov r0,#0                                       @ heap address
    mov r7, #0x2D                                   @ call system linux 'brk'
    svc #0                                          @ call system
    cmp r0,#-1                                      @ error call system
    beq 100f
    mov r3,r0                                       @ save address  heap begin
    add r0,r5                                       @ reserve r5 byte on the heap
    mov r7, #0x2D                                   @ call system linux 'brk'
    svc #0
    cmp r0,#-1
    beq 100f
                                                    @ string copy on the heap
    mov r0,r6
    mov r1,r3
1:                                                  @ loop copy string
    ldrb r2,[r0],#1                                 @ read one byte and increment pointer one byte
    strb r2,[r1],#1                                 @ store one byte and increment pointer one byte
    cmp r2,#0                                       @ end of string ?
    bne 1b                                          @ no -> loop

    add r4,r3                                        @ r4 contains address table begin
    mov r0,#0
    str r0,[r4]
    str r3,[r4,#4]
    mov r2,#1                                       @ areas counter
2:                                                  @ loop load string character
    ldrb r0,[r3]
    cmp r0,#0
    beq 3f                                          @ end string
    cmp r0,r8                                       @ separator ?
    addne r3,#1                                     @ no -> next location
    bne 2b                                          @ and loop
    mov r0,#0                                       @ store zero final of string
    strb r0,[r3]
    add r3,#1                                       @ next character
    add r2,#1                                       @ areas counter + 1
    str r3,[r4,r2, lsl #2]                          @ store address area in the table at index r2
    b 2b                                            @ and loop

3:
    str r2,[r4]                                     @ returns number areas
    mov r0,r4
100:
    pop {r1-r8,lr}
    bx lr
iTailleTable: .int 4 * NBPOSTESECLAT
/***************************************************/
/*   calcul size string                            */
/***************************************************/
/* r0 string address                 */
/* r0 returns size string            */
strLength:
    push {r1,r2,lr}
    mov r1,#0                                           @ init counter
1:
   ldrb r2,[r0,r1]                                      @ load byte of string index r1
   cmp r2,#0                                            @ end string ?
   addne r1,#1                                          @ no -> +1 counter
   bne 1b                                               @ and loop

100:
    mov r0,r1
    pop {r1,r2,lr}
    bx lr


:- object(tree_traversal).

    :- public(orders/1).
    orders(Tree) :-
        write('Pre-order:   '), pre_order(Tree), nl,
        write('In-order:    '), in_order(Tree), nl,
        write('Post-order:  '), post_order(Tree), nl,
        write('Level-order: '), level_order(Tree).

    :- public(orders/0).
    orders :-
        tree(Tree),
        orders(Tree).

    tree(
        t(1,
            t(2,
                t(4,
                    t(7, t, t),
                    t
                ),
                t(5, t, t)
            ),
            t(3,
                t(6,
                    t(8, t, t),
                    t(9, t, t)
                ),
                t
            )
        )
    ).

    pre_order(t).
    pre_order(t(Value, Left, Right)) :-
        write(Value), write(' '),
        pre_order(Left),
        pre_order(Right).

    in_order(t).
    in_order(t(Value, Left, Right)) :-
        in_order(Left),
        write(Value), write(' '),
        in_order(Right).

    post_order(t).
    post_order(t(Value, Left, Right)) :-
        post_order(Left),
        post_order(Right),
        write(Value), write(' ').

    level_order(t).
    level_order(t(Value, Left, Right)) :-
        % write tree root value
        write(Value), write(' '),
        % write rest of the tree
        level_order([Left, Right], Tail-Tail).

    level_order([], Trees-[]) :-
        (   Trees \= [] ->
            % print next level
            level_order(Trees, Tail-Tail)
        ;   % no more levels
            true
        ).
    level_order([Tree| Trees], Rest0) :-
        (   Tree = t(Value, Left, Right) ->
            write(Value), write(' '),
            % collect the subtrees to print the next level
            append(Rest0, [Left, Right| Tail]-Tail, Rest1),
            % continue printing the current level
            level_order(Trees, Rest1)
        ;   % continue printing the current level
            level_order(Trees, Rest0)
        ).

    % use difference-lists for constant time append
    append(List1-Tail1, Tail1-Tail2, List1-Tail2).

:- end_object.


variable	   'src
variable	   #src
variable     offset

: advance    1 offset +! ;
: [email protected]       offset @ 'src @ + [email protected] ;
: nextchr    advance [email protected] ;
: bound      offset @ #src @ u< ;
: separator? dup [char] | = if drop cr             else  emit      then ;
: escape?    dup [char] ^ = if drop  nextchr  emit else separator? then ;
: tokenize   0 offset ! begin bound while nextchr escape? repeat ;

\ Test of  function
Here 'src ! ," one^|uno||three^^^^|four^^^|^cuatro|" here  'src @ - #src  !
page
cr ." #### start ####" cr tokenize cr ." #### End  ####" cr