From 23f31d4ac1ac72ca13005bea218b9c2363fa940e Mon Sep 17 00:00:00 2001 From: han semaj Date: Fri, 22 Aug 2014 21:51:12 +1200 Subject: [PATCH] Reimplement butlast in terms of drop-last --- docs/language/core.rst | 25 +++++++++++++++++++++++++ hy/core/language.hy | 2 +- tests/native_tests/core.hy | 13 +++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/docs/language/core.rst b/docs/language/core.rst index 0f0f91c..14da12c 100644 --- a/docs/language/core.rst +++ b/docs/language/core.rst @@ -6,6 +6,31 @@ Hy Core Core Functions =============== +.. _butlast-fn: + +butlast +------- + +Usage: ``(butlast coll)`` + +Returns an iterator of all but the last item in ``coll``. + +.. code-block:: hy + + => (list (butlast (range 10))) + [0, 1, 2, 3, 4, 5, 6, 7, 8] + + => (list (butlast [1])) + [] + + => (list (butlast [])) + [] + + => (import itertools) + => (list (take 5 (butlast (itertools.count 10)))) + [10, 11, 12, 13, 14] + + .. _is-coll-fn: coll? diff --git a/hy/core/language.hy b/hy/core/language.hy index 9386558..99441a4 100644 --- a/hy/core/language.hy +++ b/hy/core/language.hy @@ -38,7 +38,7 @@ (defn butlast [coll] "Returns coll except of last element." - (itertools.islice coll 0 (dec (len coll)))) + (drop-last 1 coll)) (defn coll? [coll] "Checks whether item is a collection" diff --git a/tests/native_tests/core.hy b/tests/native_tests/core.hy index 3dc8c13..f96d309 100644 --- a/tests/native_tests/core.hy +++ b/tests/native_tests/core.hy @@ -38,6 +38,19 @@ (assert-false (coll? "abc")) (assert-false (coll? 1))) +(defn test-butlast [] + "NATIVE: testing butlast function" + (assert-equal (list (butlast (range 10))) + [0 1 2 3 4 5 6 7 8]) + (assert-equal (list (butlast [1])) + []) + (assert-equal (list (butlast [])) + []) + ; with an infinite sequence + (import itertools) + (assert-equal (list (take 5 (butlast (itertools.count 10)))) + [10 11 12 13 14])) + (defn test-cycle [] "NATIVE: testing cycle" (assert-equal (list (cycle [])) [])