Skip to content

Commit

Permalink
feat(stdlib): add Queue.size and Stack.size (#647)
Browse files Browse the repository at this point in the history
* feat: add Queue.size function

* feat: add Stack.size function
  • Loading branch information
ashutoshvarma committed May 7, 2021
1 parent 3a8da65 commit 82ed533
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
6 changes: 6 additions & 0 deletions compiler/test/stdlib/queue.test.gr
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,9 @@ assert Queue.isEmpty(Queue.pop(Queue.push(1, empty)))
assert Queue.isEmpty(Queue.pop(Queue.pop(Queue.pop(sampleQueue))))
assert Queue.peek(Queue.pop(sampleQueue)) == Some(2)
assert Queue.peek(Queue.pop(Queue.push(4, Queue.pop(sampleQueue)))) == Some(3)

// Queue.size

assert Queue.size(empty) == 0
assert Queue.size(sampleQueue) == 3
assert Queue.size(Queue.pop(Queue.pop(sampleQueue))) == 1
6 changes: 6 additions & 0 deletions compiler/test/stdlib/stack.test.gr
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,9 @@ assert Stack.isEmpty(Stack.pop(Stack.push(1, empty)))
assert Stack.isEmpty(Stack.pop(Stack.pop(Stack.pop(sampleStack))))
assert Stack.peek(Stack.pop(sampleStack)) == Some(2)
assert Stack.peek(Stack.pop(Stack.push(4, Stack.pop(sampleStack)))) == Some(2)

// Stack.size

assert Stack.size(empty) == 0
assert Stack.size(sampleStack) == 3
assert Stack.size(Stack.pop(Stack.pop(sampleStack))) == 1
9 changes: 9 additions & 0 deletions stdlib/queue.gr
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,12 @@ export let pop = (queue) => {
@deprecated Please use `Queue.pop` instead. `Queue.dequeue` will be removed in v0.4.0.
*/
export let dequeue = pop;

export let size = (queue) => {
match (queue) {
{ forwards: [], backwards: [] } => 0,
{ forwards, backwards: [] } => List.length(forwards),
{ forwards: [], backwards } => List.length(backwards),
{ forwards, backwards } => List.length(forwards) + List.length(backwards),
}
}
7 changes: 7 additions & 0 deletions stdlib/stack.gr
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,10 @@ export let pop = (stack) => {
{ data: [head, ...tail] } => { data: tail, }
}
}

export let size = (stack) => {
match (stack) {
{ data: [] } => 0,
{ data } => List.length(data)
}
}

0 comments on commit 82ed533

Please sign in to comment.