Thursday, May 29, 2014

Simple Linked List

class Node implements Cloneable {
    private int val
    private int i
    private Node prev
    private Node next
    
    private static Node head
    private static Node last
    
    Node(int val, int i = 0) {
        if (!head) head = this
        if (!last) last = this
        
        this.i = i
        this.val = val
    }
    
    Integer at(int x, Node node = this) {
        //println "" + x + node.i + node.next
        
        if (x > node.i) {
            if (node.next != null) 
                return this.at(x, node.next)
            else 
                return null
        }

        return node.val
    }
    
    Node add(int val) {
        Node newNode = new Node(val, last.i + 1)
        
        newNode.prev = last
        last.next = newNode
        
        last = newNode
        
        //println "---\nadd done\n---"
        
        return head
    }
    
    Node reverse() {
        Node r = last.clone()
        Node prev = last.prev
        
        while (prev != null) {
            r.add(prev.val)
            prev = prev.prev    
        }
        
        return r
    }
}



Node list = new Node(1)

assert list.at(0) == 1

list.add(4).add(6) // chained adding

assert list.at(0) == 1

assert list.at(1) == 4

assert list.at(2) == 6

assert list.at(3) == null

assert list.reverse().at(0) == list.at(2)

Persistent (Immutable) Collections

@Grapes(
    @Grab(group='org.pcollections', module='pcollections', version='2.1.2')
)
import org.pcollections.*

PSet set = HashTreePSet.empty()
set = set + "something"
println set
println(set + "something else")
println set // immutable

Wednesday, May 28, 2014

GPars Actors

import static groovyx.gpars.actor.Actors.actor

/**
 * A demo showing two cooperating actors. The decryptor decrypts received messages and replies them back.
 * The console actor sends a message to decrypt, prints out the reply and terminates both actors.
 * The main thread waits on both actors to finish using the join() method to prevent premature exit,
 * since both actors use the default actor group, which uses a daemon thread pool.
 * 
 * code derrived from: http://gpars.codehaus.org/Actor
 */

def decryptor = actor {
    loop {
        react {message ->
            Thread.sleep(1000);
            
            if (!(message instanceof String)) {
                stop()
                return
            }
            
            reply message.reverse()
        }
    }
}

def console = actor {
    List strs = ['abc','zyx','Vvv',false];
    int i = -1
    
    loop {
        if (!strs[++i]) stop()
        
        decryptor << strs[i]
        
        println "Sent: ${strs[i]}"
        
        react {msg ->
           println "Decrypted msg: $msg"
        }
    }
}

[decryptor, console]*.join()