Skip to content

Commit

Permalink
Feature/init array default values (#296)
Browse files Browse the repository at this point in the history
* Initialization of arrays

---------

Co-authored-by: phischu <[email protected]>
  • Loading branch information
IR0NSIGHT and phischu authored Nov 10, 2023
1 parent cf3b7d1 commit 03d9349
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
3 changes: 3 additions & 0 deletions examples/pos/arrays.check
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@ Some(hello)
Some(world)
None()
Some(foo)
Hello World,Hello World,Hello World,Hello World
0,1,2,3,4
1,5,17
9 changes: 9 additions & 0 deletions examples/pos/arrays.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,13 @@ def main() = {
println(show(get(arr, 4)));
put(arr, 4, "foo");
println(show(get(arr, 4)))

val arrWithVals = arrayFromValue(4,"Hello World");
println(arrWithVals)

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

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

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

}
};
worker(list,0){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
23 changes: 23 additions & 0 deletions libraries/js/mutable/array.effekt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,29 @@ extern type Array[T]

def emptyArray[T](): Array[T] = emptyArray(0)

//initialize array with default values
def arrayFromValue[T](size: Int, default: T) : Array[T] = {
val arr = emptyArray[T](size)
each(0,arr.size()){ i=> put(arr, i, default)}
return arr;
}

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){(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 03d9349

Please sign in to comment.