All entries for Sunday 06 August 2006
August 06, 2006
Loopy linked lists
I've been playing with Nemerle today. It's a functional/OO hybrid for the .NET CLR. I needed a circular linked list for a project I'm working on. Basically a linked list where the end points back to the start.Whilst Nemerle allows mutable variables, I felt dirty leaving all the beauty of "no side effects" programming behind. Luckily Nemerle allows lazy evaluation using some macro magic behind the scenes (That's right Dan, I said the "L" word ;)). This meant I could reference the first item effectively inside its own definition. (The laziness is not exactly first class like in Haskell, but it certainly works for me here.)
#pragma indent
using System
using Nemerle
class LoopList[T]
private first : LazyValue[LoopListItem[T]]
public this(values : list [T])
def build(xs)
| [] => first
| head::tail => lazy( LoopListItem(head, build(tail)) )
first = build(values)
public First : LoopListItem[T]
get
first
[Record] struct LoopListItem[T]
public Value : T
public Next : LazyValue[LoopListItem[T]]
// Test code:
mutable item = LoopList([1,2,3]).First
repeat(10)
Console.Write($"$(item.Value) ")
item = item.Next
// Outputs:
// 1 2 3 1 2 3 1 2 3 1
Next I need to figure out a circular doubly linked list…