# HG changeset patch # User IBBoard # Date 1559998825 -3600 # Node ID cf7182bca068045023790d0aa0c989ba40a47147 # Parent 0f57e5c2ae82a503d68658b673e4b09b74fc3508 Notes on infinite sequences Plus a clarification on "some" diff -r 0f57e5c2ae82 -r cf7182bca068 6-Clojure/README.txt --- a/6-Clojure/README.txt Thu Jun 06 20:56:16 2019 +0100 +++ b/6-Clojure/README.txt Sat Jun 08 14:00:25 2019 +0100 @@ -89,7 +89,9 @@ (some nil? [1 2 nil]) ; true -This seems oddly inconsistent. The footnote explains that it's because "some returns the first value that is not nil or false", so "nil?" return false for 1 and 2 and then return true for nil and so some returns it. +This seems oddly inconsistent. The footnote explains that it's because "some returns the first value that is not nil or false", so "nil?" return false for 1 and 2 and then return true for nil and so some returns true. +With other "some" filters, like "(some odd? …)", it works because nil (if it doesn't find anything) is falsey and numbers (if it finds an odd one) are truthy. + It's not a predicate because "(some nil? [1 2]) returns nil, not false. Functional languages do lazy tail recursion. Unless they're Clojure, because the JVM doesn't support it. Clojure does it with a "loop" and a "recur" function. "loop" takes x and y with initial values and a function to call. See loop_recur.clj. @@ -104,4 +106,14 @@ (reduce + [1 2 3 4]) ; sums (reduce * [1 2 3 4 5]) ; factorial -As well as sorting a list with (sort list) you can use a custom funcion with (sort-by function list) where "function" takes a single parameter and generates a key. \ No newline at end of file +As well as sorting a list with (sort list) you can use a custom funcion with (sort-by function list) where "function" takes a single parameter and generates a key. + +Infinite sequences can be built with (repeat obj), (cycle [list]) and (iterate func start_obj). (take count list) takes the number of items that you want from a potentially infinite sequence (which is lazily evaluated). There's also a (drop count list) function to skip items. +If you don't like the "inside function happens first" Lisp-like function order then the slightly bizarre "->>" function (left-to-right operator) applies a number of functions in order, e.g.: + +(->> [:later :rinse : repeat] (cycle) (drop 2) (take 5)) +; equivalent to (take 5 (drop 2 (cycle [:later :rinse : repeat]))) + +You can also (interpose obj list) to insert something between each item and (interleave list list) to interleave two lists. + +The book seems to use "(take n (iterate inc m))" rather than "(range m n+1)" but doesn't say why. Range is lazy, as is iterate. The only benefit to iterate is if you're doing an 'infinite' list with a high start, as it starts high rather than spending time generating and dropping. \ No newline at end of file