Created
March 4, 2014 17:14
-
-
Save rigibun/9350976 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class List(T) { | |
public T head; | |
public List!(T) tail; | |
public this(T val) { | |
this.head = val; | |
this.tail = null; | |
} | |
public this(T[] arr) { | |
if(arr.length - 1 == 0){ | |
this.head = arr[0]; | |
this.tail = null; | |
} else { | |
this.head = arr[0]; | |
this.tail = new List!T(arr[1 .. $]); | |
} | |
} | |
private this(T val, List!T list) { | |
this.head = val; | |
this.tail = list; | |
} | |
private this(List!T list) { | |
this.head = list.head; | |
if(list.tail) | |
this.tail = new List!T(list.tail); | |
} | |
private List!T junction(List!T list) { | |
if(this.tail) { | |
return this.tail.junction(this, list); | |
} else { | |
this.tail = list; | |
return this; | |
} | |
} | |
private List!T junction(List!T ret, List!T list) { | |
if(this.tail) { | |
return this.tail.junction(ret, list); | |
} else { | |
this.tail = list; | |
return ret; | |
} | |
} | |
public List!T dup() { | |
return new List!T(this); | |
} | |
public static List!T cons(T val, List!T list) { | |
return new List!T(val, list); | |
} | |
public static List!T cons(T val1, T val2) { | |
return new List!T([val1, val2]); | |
} | |
public static List!T cons(List!T list1, List!T list2) { | |
return list1.dup.junction(list2); | |
} | |
public void for_each(void delegate(T) del) { | |
del(this.head); | |
if(this.tail !is null) | |
this.tail.for_each(del); | |
} | |
public void for_each(void function(T) func) { | |
func(this.head); | |
if(this.tail !is null) | |
this.tail.for_each(func); | |
} | |
public T foldl(T accum, T delegate(T, T) del) { | |
return this.tail? | |
(this.tail.foldl(del(accum, this.head), del)) | |
: del(accum, this.head); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment