Skip to content

Commit

Permalink
Merge pull request #662 from In-Veritas/main
Browse files Browse the repository at this point in the history
Adds builtin functions Tree/reverse and Tree/to_list
  • Loading branch information
developedby authored Aug 7, 2024
2 parents b4a20f1 + 63ba5d2 commit 270f39c
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
32 changes: 29 additions & 3 deletions src/fun/builtins.bend
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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

Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions tests/golden_tests/run_file/tree_to_list.bend
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def main:
var = Tree/reverse(![![!1, !2],![!3, !4]])
return Tree/to_list(var)

9 changes: 9 additions & 0 deletions tests/snapshots/run_file__tree_to_list.bend.snap
Original file line number Diff line number Diff line change
@@ -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]

0 comments on commit 270f39c

Please sign in to comment.