diff --git a/src/fun/builtins.bend b/src/fun/builtins.bend index 89c04fd15..2a5f90cc1 100644 --- a/src/fun/builtins.bend +++ b/src/fun/builtins.bend @@ -76,10 +76,20 @@ String/split s delim = (String/split.go s delim (List/Cons String/Nil List/Nil)) # Create a new difference list DiffList/new = λx x +# DiffList/wrap(head: T) -> (List(T) -> List(T) +# Creates a new difference list with just the given value. +def DiffList/wrap(head): + return lambda tail: List/Cons(head, tail) + # DiffList/append(diff: List(T) -> List(T), val: T) -> (List(T) -> List(T)) # Append a value to the end of the difference list DiffList/append diff val = λx (diff (List/Cons val x)) +# DiffList/append(left: List(T) -> List(T), right: List(T) -> List(T)) -> (List(T) -> List(T)) +# Concatenates two difference lists. +def DiffList/concat(left, right): + return lambda x: left(right(x)) + # DiffList/cons(diff: List(T) -> List(T), val: T) -> (List(T) -> List(T)) # Append a value to the beginning of the difference list DiffList/cons diff val = λx (List/Cons val (diff x)) @@ -96,6 +106,22 @@ type Tree: Node { ~left, ~right } Leaf { value } +# Returns a List converted from a Tree. +def Tree/to_list(tree): + fold tree: + case Tree/Leaf: + list = DiffList/wrap(tree.value) + case Tree/Node: + list = DiffList/concat(tree.left, tree.right) + return DiffList/to_list(list) + +# Reverses a tree swapping right and left leaves. +def Tree/reverse(tree): + fold tree: + case Tree/Leaf: + return !tree.value + case Tree/Node: + return ![tree.right, tree.left] # MAP Impl @@ -217,11 +243,11 @@ IO/FS/STDOUT = 1 IO/FS/STDERR = 2 ### Seek modes -# Seek from start of file +# Seek from start of file. IO/FS/SEEK_SET = +0 -# Seek from current position +# Seek from current position. IO/FS/SEEK_CUR = +1 -# Seek from end of file +# Seek from end of file. IO/FS/SEEK_END = +2 ### File utilities diff --git a/tests/golden_tests/run_file/tree_to_list.bend b/tests/golden_tests/run_file/tree_to_list.bend new file mode 100644 index 000000000..afcd27eec --- /dev/null +++ b/tests/golden_tests/run_file/tree_to_list.bend @@ -0,0 +1,4 @@ +def main: + var = Tree/reverse(![![!1, !2],![!3, !4]]) + return Tree/to_list(var) + \ No newline at end of file diff --git a/tests/snapshots/run_file__tree_to_list.bend.snap b/tests/snapshots/run_file__tree_to_list.bend.snap new file mode 100644 index 000000000..9da109da0 --- /dev/null +++ b/tests/snapshots/run_file__tree_to_list.bend.snap @@ -0,0 +1,9 @@ +--- +source: tests/golden_tests.rs +input_file: tests/golden_tests/run_file/tree_to_list.bend +--- +NumScott: +[4, 3, 2, 1] + +Scott: +[4, 3, 2, 1]