]> xenbits.xensource.com Git - xcp/xen-api-libs.git/commitdiff
Adds take and tails to our extended list module
authorMatthias Goergens <matthias.goergens@citrix.com>
Tue, 2 Feb 2010 16:00:16 +0000 (16:00 +0000)
committerMatthias Goergens <matthias.goergens@citrix.com>
Tue, 2 Feb 2010 16:00:16 +0000 (16:00 +0000)
`take' gives the first n elements of a list (or less if the list is
shorter).  `tails' gives a list of all suffixes of a list.

Signed-off-by: Matthias Goergens <matthias.goergens@citrix.com>
stdext/listext.ml
stdext/listext.mli

index e1f7532ee1d76c2163ae91b22b51c4ac2a347880..29ad0eeb349a141ac69a9d4eb73dd02e3f6a9f6b 100644 (file)
@@ -11,6 +11,7 @@
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU Lesser General Public License for more details.
  *)
+open Fun
 module List = struct include List
 
 (** Turn a list into a set *)
@@ -174,4 +175,21 @@ let assoc_default k l d =
 (* Like the Lisp cons *)
 let cons a b = a :: b
 
+(* Could use fold_left to get the same value, but that would necessarily go through the whole list everytime, instead of the first n items, only. *)
+(* ToDo: This is complicated enough to warrant a test. *)
+(* Is it wise to fail silently on negative values?  (They are treated as zero, here.)
+   Pro: Would mask fewer bugs.
+   Con: Less robust.
+*)
+let take n list =
+    let rec helper i acc list =
+       if i <= 0 || list = []
+       then acc
+       else helper (i-1)  (List.hd list :: acc) (List.tl list)
+    in List.rev $ helper n [] list
+
+(* Thanks to sharing we only use linear space. (Roughly double the space needed for the spine of the original list) *)
+let rec tails = function
+    | [] -> [[]]
+    | (_::xs) as l -> l :: tails xs
 end
index b1097b67f7c326f4fd90e5984795b617eccf6d54..c8b4ced3ddb683924a17b94a66aa5e0cb0ed5648 100644 (file)
@@ -172,4 +172,9 @@ module List :
     (* Like Lisp cons*)
     val cons : 'a -> 'a list -> 'a list
 
+    (* take n list: Return the first n elements of list (or less if list is shorter).*)
+    val take : int -> 'a list -> 'a list
+       
+    val tails : 'a list -> ('a list) list
+
   end