2018-11-01 14:55:45 +00:00
|
|
|
//---------------------------------------------------------------------------
|
|
|
|
// @syndicate-lang/core, an implementation of Syndicate dataspaces for JS.
|
2021-01-11 22:35:36 +00:00
|
|
|
// Copyright (C) 2016-2021 Tony Garnock-Jones <tonyg@leastfixedpoint.com>
|
2018-11-01 14:55:45 +00:00
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
//---------------------------------------------------------------------------
|
|
|
|
|
2021-01-11 22:35:36 +00:00
|
|
|
export type NonEmptyStack<T> = { item: T, rest: Stack<T> };
|
|
|
|
export type Stack<T> = null | NonEmptyStack<T>;
|
2018-10-22 14:29:07 +00:00
|
|
|
|
2021-01-11 22:35:36 +00:00
|
|
|
export function empty<T>(): Stack<T> {
|
|
|
|
return null;
|
|
|
|
}
|
2019-06-14 14:33:02 +00:00
|
|
|
|
2021-01-11 22:35:36 +00:00
|
|
|
export function push<T>(item: T, rest: Stack<T>): NonEmptyStack<T> {
|
|
|
|
return { item, rest };
|
|
|
|
}
|
2018-10-22 14:29:07 +00:00
|
|
|
|
2021-01-15 12:38:15 +00:00
|
|
|
export function isEmpty<T>(s: Stack<T>): s is null {
|
|
|
|
return s === null;
|
|
|
|
}
|
|
|
|
|
2021-01-11 22:35:36 +00:00
|
|
|
export function nonEmpty<T>(s: Stack<T>): s is NonEmptyStack<T> {
|
2021-01-15 12:38:15 +00:00
|
|
|
return s !== null;
|
2018-10-22 14:29:07 +00:00
|
|
|
}
|
|
|
|
|
2021-01-11 22:35:36 +00:00
|
|
|
export function rest<T>(s: Stack<T>): Stack<T> {
|
|
|
|
if (nonEmpty(s)) {
|
|
|
|
return s.rest;
|
2018-10-22 14:29:07 +00:00
|
|
|
} else {
|
2021-01-11 22:35:36 +00:00
|
|
|
throw new Error("pop from empty Stack");
|
2018-10-22 14:29:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-11 22:35:36 +00:00
|
|
|
export function drop<T>(s: Stack<T>, n: number): Stack<T> {
|
|
|
|
while (n--) s = rest(s);
|
|
|
|
return s;
|
|
|
|
}
|
2018-10-22 14:29:07 +00:00
|
|
|
|
2021-01-11 22:35:36 +00:00
|
|
|
export function dropNonEmpty<T>(s: NonEmptyStack<T>, n: number): NonEmptyStack<T> {
|
|
|
|
while (n--) {
|
2021-01-15 12:38:15 +00:00
|
|
|
const next = s.rest;
|
|
|
|
if (!nonEmpty(next)) throw new Error("dropNonEmpty popped too far");
|
|
|
|
s = next;
|
2021-01-11 22:35:36 +00:00
|
|
|
}
|
|
|
|
return s;
|
|
|
|
}
|