Basic Clojure functions and immutability

There are many operations we can perform over our result list (or lazy sequence). One of the main approaches of functional programming (FP) is to take a data structure and perform operations over it to produce a new data structure or atomic result (such as a string, number, and so on). This may sound inefficient at first. However, most FP languages employ something called immutability to make these operations efficient. Immutable data structures are those that cannot change once they've been created. This is feasible as most immutable FP languages use some kind of structural data sharing between an original and a modified version. The idea is that if we run evaluate (conj [1 2 3] 4), the resulting [1 2 3 4] vector shares the original vector of [1 2 3]. The only additional resource that's assigned is for any novelty that's been introduced in the data structure (4). There's a more detailed explanation of, for example, Clojure's persistent vectors here: http://hypirion.com/musings/understanding-persistent-vector-pt-1:

  • conj: This conjoins an element to a collection—the collection decides where. So, conjoining an element to a (conj [1 2 3] 4) vector versus conjoining an element to a (conj '(1 2 3) 4) list yields different results. Try doing this in your REPL.
  • map: This passes a function over one or many lists, yielding another list. Evaluating (map inc [1 2 3]) increments each element by 1.
  • reduce (or left fold): This passes a function over each element, accumulating one result. Evaluating (reduce + (take 100 (repeatedly (fn [] (rand 35))))) sums the list.
  • filter: This constrains an input by providing some condition.
  • >=: This is a conditional function that tests whether the first argument is greater than, or equal to the second function. Try (>= 4 9) and (>= 9 1).
  • fn: This is a function that creates a function. This unnamed or anonymous function can have any instructions that you choose to put in it.

So, if we only want numbers above 12, we can add this assertion to a predicate function. Try entering the following expression into your REPL:

  (take 25 (filter (fn [x] (>= x 12))
                   (repeatedly (fn [] (rand 35)))))
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.91.254