# HG changeset patch # User Steve Losh # Date 1470673787 0 # Node ID a25df85e26e5efff271fbfe6125425f649c50918 # Parent e5c5cf8143a2acf144d3d208d1d91174c03dc84a Add take, fix a bug diff -r e5c5cf8143a2 -r a25df85e26e5 losh.lisp --- a/losh.lisp Mon Aug 08 13:39:27 2016 +0000 +++ b/losh.lisp Mon Aug 08 16:29:47 2016 +0000 @@ -136,6 +136,8 @@ plus)) + + ;;;; Functions (defun juxt (&rest fns) "Return a function that will juxtipose the results of `functions`. @@ -217,6 +219,25 @@ (collect `(zap% ,place ,function %))))) +;;;; Lists +(defun take (n list) + "Return a fresh list of the first `n` elements of `list`. + + If `list` is shorter than `n` a shorter result will be returned. + + Example: + + (take 2 '(a b c)) + => (a b) + + (take 4 '(1)) + => (1) + + " + (iterate (repeat n) + (for item :in list) + (collect item))) + ;;;; Hash Tables (defmacro gethash-or-init (key hash-table default-form) "Get `key`'s value in `hash-table`, initializing if necessary. @@ -390,6 +411,40 @@ (terminate)))))))) +;;;; Distributions +(defun prefix-sums (list) + "Return a list of the prefix sums of the numbers in `list`. + + Example: + + (prefix-sums '(10 10 10 0 1)) + => (10 20 30 30 31) + + " + (iterate + (for i :in list) + (sum i :into s) + (collect s))) + +(defun frequencies (seq &key (test 'eql)) + "Return a hash table containing the feqeuencies of the items in `seq`. + + Uses `test` for the `:test` of the hash table. + + Example: + + (frequencies '(foo foo bar)) + => {foo 2 + bar 1} + + " + (iterate + (with result = (make-hash-table :test test)) + (for i :in-whatever seq) + (incf (gethash i result 0)) + (finally (return result)))) + + ;;;; Hash Sets (defclass hash-set () ((data :initarg :data))) diff -r e5c5cf8143a2 -r a25df85e26e5 package.lisp --- a/package.lisp Mon Aug 08 13:39:27 2016 +0000 +++ b/package.lisp Mon Aug 08 16:29:47 2016 +0000 @@ -32,6 +32,8 @@ #:mulf #:zapf + #:take + #:gethash-or-init #:queue @@ -55,6 +57,9 @@ #:in-sequences #:in-whatever + #:prefix-sums + #:frequencies + #:hash-set #:make-set #:set-contains-p