From d07c6e8a0ede3114ebfd8c3ea6cc161cf009f072 Mon Sep 17 00:00:00 2001 From: Lenny222 Date: Thu, 29 Dec 2011 21:24:03 +0100 Subject: list: use predicate to enforce non-empty requirement --- src/libstd/list.rs | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) (limited to 'src/libstd') diff --git a/src/libstd/list.rs b/src/libstd/list.rs index c6a24d275eb..f6b46ed7d2e 100644 --- a/src/libstd/list.rs +++ b/src/libstd/list.rs @@ -97,6 +97,27 @@ fn has(ls: list, elt: T) -> bool { ret false; } +/* +Function: is_empty + +Returns true if the list is empty. +*/ +pure fn is_empty(ls: list) -> bool { + alt ls { + nil. { true } + _ { false } + } +} + +/* +Function: is_not_empty + +Returns true if the list is not empty. +*/ +pure fn is_not_empty(ls: list) -> bool { + ret !is_empty(ls); +} + /* Function: len @@ -112,8 +133,11 @@ Function: tail Returns all but the first element of a list */ -pure fn tail(ls: list) -> list { - alt ls { cons(_, tl) { ret *tl; } nil. { fail "list empty" } } +pure fn tail(ls: list) : is_not_empty(ls) -> list { + alt ls { + cons(_, tl) { ret *tl; } + nil. { fail "list empty" } + } } /* @@ -121,8 +145,11 @@ Function: head Returns the first element of a list */ -pure fn head(ls: list) -> T { - alt ls { cons(hd, _) { ret hd; } nil. { fail "list empty" } } +pure fn head(ls: list) : is_not_empty(ls) -> T { + alt ls { + cons(hd, _) { ret hd; } + nil. { fail "list empty" } + } } /* -- cgit 1.4.1-3-g733a5