Skip to content

Commit

Permalink
init array for immutable list
Browse files Browse the repository at this point in the history
  • Loading branch information
IR0NSIGHT committed Oct 25, 2023
1 parent 05238e7 commit f1496e0
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 4 deletions.
3 changes: 2 additions & 1 deletion examples/pos/arrays.check
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ Some(world)
None()
Some(foo)
Hello World,Hello World,Hello World,Hello World
0,1,2,3,4
0,1,2,3,4
1,5,17
7 changes: 5 additions & 2 deletions examples/pos/arrays.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ def main() = {
val arrWithVals = initArray(4,"Hello World");
println(arrWithVals)

val arrByF = initArray(5){ i => i};
println(arrByF)
val arrByF = arrayFromLoop(5){ i => i};
println(arrByF);

var arrByList = arrayFromList([1,5,17]);
println(arrByList)
}
8 changes: 8 additions & 0 deletions libraries/js/immutable/list.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ def foreach[A](l: List[A]) { f: A => Unit } : Unit = {
}
}

def foreachIndex[T](list: List[T], i: Int){ f: (Int, T) => Unit}: Unit = {
list match {
case Nil() => ();
case Cons(head, tail) => f(i, head); foreachIndex(tail, i+1){f}

}
}

def map[A, B](l: List[A]) { f: A => B } : List[B] = {
var acc = Nil[B]()
l.foreach { el => acc = Cons(f(el), acc) }
Expand Down
12 changes: 11 additions & 1 deletion libraries/js/mutable/array.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,22 @@ def initArray[T](size: Int, default: T) : Array[T] = {
return arr;
}

def initArray[T](size: Int) { index: Int => T}: Array[T] = {
def arrayFromLoop[T](size: Int) { index: Int => T}: Array[T] = {
val arr = emptyArray[T](size)
each(0,arr.size()){ i=> put(arr, i, index(i))}
return arr
}

def arrayFromList[T](list: List[T]): Array[T] = {
val listSize = list.size();
val arr = emptyArray(listSize);

foreachIndex(list, 0){(i, head) => put(arr, i, head)}
return arr;
}



extern pure def emptyArray[T](initialSize: Int): Array[T] =
"(new Array(initialSize))"

Expand Down

0 comments on commit f1496e0

Please sign in to comment.