How to make list of partial functions in Clojure? - clojure

i need to write code like this in clojure.
-- haskell
fns = map (,) [1..3]
head fns $ 1
-- => (1,1)
fns <*> [1..3]
-- => [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
doesn't work
(def fns (map (partial list) (range 1 3)))
((first fns) 1)
;; => ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn
works, but i think this isn't idiomatic way
(def fns (map (fn [x] `(partial list ~x)) (range 1 3)))
((eval (first fns)) 1)
;; => (1 1)

The function (partial list) is equivalent to just the function list. It's not like haskell where everything is curried - I think you intended partial to see that it's been given only one argument, list, and curry itself up to wait for a second argument. But really that should be (partial partial list): you are attempting to partially apply the function partial itself.
Note also that partially-applied functions are not as common in clojure as they are in haskell, partly because they just don't read so well. Instead of (map (partial partial list) (range 1 3)), if I wanted to build a list of functions like this, I would probably write (for [i (range 1 3)] (fn [j] (list i j))).

Related

How to return same list by using reduce function in Clojure?

In DrRacket to return the list without changing by using foldr done this way:
(foldr cons '() '(1 2 3))
However in Clojure reduce is fold left so how can I do this?
First I tried this:
(reduce cons '() '(1 2 3))
=> IllegalArgumentException Don't know how to create ISeq from: java.lang.Long clojure.lang.RT.seqFrom (RT.java:542)
Afterward I tried this:
(reduce conj '() '(1 2 3))
=> (3 2 1)
"=>" is the output in REPL
No I don't want to read how Clojure implements reduce. I already know that. This is a more specific question. I found the answer myself, I will post it.
In your second attempt you had to "flip" the arguments passed to cons for things to work:
(reduce #(cons %2 %1) '() '(1 2 3))
=> (3 2 1)
However, as you noticed, reduce is actually a fold-left, so the first item in the original list, becomes the inner-most (or last) item in the result list. This could be handled with reverse:
(reduce (fn[a b](cons b a)) '() (reverse '(1 2 3)))
=> (1 2 3)
You can read more about why clojure 'lacks' foldr in here
I'm not that familiar with Racket, but Clojure's reduce appears to differ from Racket's foldr in two major ways:
reduce processes the list from head to tail (vs. tail to head for foldr). In this respect, reduce is similar to foldl.
reduce passes the accumulated value as the first argument to the reducing function (vs. the last argument for foldr/foldl).
The second difference is the reason for the error when using cons -- (cons '() 1) is the first call made, and 1 obviously isn't a list.
If we consider that (conj xs x) is equivalent to (cons x xs) when xs is a list, then (reduce conj '() '(1 2 3)) is equivalent to (cons 3 (cons 2 (cons 1 '()))) which might be more apparent when written as
(->> '()
(cons 1)
(cons 2)
(cons 3))
Now, if you don't mind the result being a vector instead of a list, you could do:
(reduce conj [] '(1 2 3))
Or, if you prefer, you could convert the result into a seq so that it essentially behaves like a list:
(seq (reduce conj [] '(1 2 3)))
Alternatively, you could reverse the input list:
(reduce conj () (reverse '(1 2 3)))
Here is my solution. I don't know how efficient it. We used this kind of solutions in University during Racket lessons.
(reduce #(concat %1 (list %2)) '() '(1 2 3))
=> (1 2 3)

Attempting to call unbound fn, while I have defined it

I am trying to convert SICP's meta-circular evaluator to Clojure. In setup-environment a call to extend-environment does not compile because I get the error "Attempting to call unbound fn". Here's part of the code:
(... loads of methods for creating and managing environment list)
(def primitive-procedures
(list (list 'car first)
(list 'cdr rest)
(list 'cons conj) ;; TODO: reverse
(list 'null? nil?)
(list 'list list)
(list '+ +)
(list '- -)
(list '* *)
(list '/ /)
;; more primitives
))
(def primitive-procedure-names
#(map [first
primitive-procedures]))
(def primitive-procedure-objects
(fn [] (map (fn [p] (list 'primitive (second p)))
primitive-procedures)))
(def the-empty-environment '())
(defn extend-environment [vars vals base-env]
(if (= (count vars) (count vals))
(conj base-env (make-frame vars vals))
(if (< (count vars) (count vals))
(throw (Throwable. "Too many arguments supplied") vars vals)
(throw (Throwable. "Too few arguments supplied") vars vals))))
;; Added # in front here so it could be called (???)
(defn setup-environment []
#(let [initial-env
(extend-environment (primitive-procedure-names)
(primitive-procedure-objects)
the-empty-environment)] ;; <= that does not work
(define-variable! 'true true initial-env)
(define-variable! 'false false initial-env)
initial-env)))
;; Method for interacting with the evaluator:
(defn driver-loop []
(prompt-for-input input-prompt)
(let [input (read)]
(let [output (m-eval input the-global-environment)]
(announce-output output-prompt)
(user-print output)))
(driver-loop))
(...)
(def the-global-environment (setup-environment))
(driver-loop)
And when I evaluate the extend-environment method I get the following error:
Caused by java.lang.IllegalStateException
Attempting to call unbound fn:
#'scheme-evaluator/extend-environment
Var.java: 43 clojure.lang.Var$Unbound/throwArity
AFn.java: 40 clojure.lang.AFn/invoke
scheme-evaluator.clj: 277 scheme-evaluator/eval7808
I think I am not providing the right type of parameters or I have not created the right type of function. I tried various variations of anonymous methods and passing in parentheses or without, but I don't get it to compile.
Does anyone know what the reason is for this error and how can I fix it?
The definition of
(def primitive-procedure-names
#(map [first
primitive-procedures]))
likely does not do what you intend. As written this defines a function that takes no arguments and returns transducer (which is a function) that will, if applied to a sequence substitute the values 0 and 1 for the functions first and primitive-procedures respectively. I'll demonstrate first with functions and then with values of numbers to make what's happening more clear (hopefully):
user> (into [] (map [first 'example]) [0 1])
[#function[clojure.core/first--4339] example]
user> (into [] (map [1 2]) [0 1])
[1 2]
perhaps you wanted
(def primitive-procedure-names
(map first primitive-procedures))
And may I suggest using the defn form for defining functions and the def form for defining values unless you have a really strong reason not to.
setup-environment is a function that returns a function which will if you call that function return a function that return's the initial-environment unmodified by the calls to define-variable. In Clojure the collection types are immutable so if you want to make several changes to a collection it's necessary to chain the result of adding the first one into the imput of adding the second one, then return the result of adding the second one:
(add-second (add-first initial-value))
which can also be written like this:
(-> initial-value
add-first
add-second)
which is just a shorthand for the example above.

clojure list operation result not equal

I test some list operation, find this difference with two syntax。
(conj (cons 321321 [1]) 123123123)
=> (123123123 321321 1)
and
(cons 321321 [1])
=> (321321 1)
(conj [321312 1] 123123123)
=> [321312 1 123123123]
why these result isn't equal?
Because you are doing different things.
cons http://clojuredocs.org/clojure.core/cons
Returns a new seq where x is the first element and seq is
the rest.
conj http://clojuredocs.org/clojure.core/conj
Returns a new collection with the xs
'added'. (conj nil item) returns (item). The 'addition' may
happen at different 'places' depending on the concrete type.
in your first example you are "prepending" a new entry (easiest way for conj to add to a sequence) and in your second example you are "appending" to a vector (again easiest way for conj to add).
user=> (.getClass (cons 321321 [1]))
clojure.lang.Cons
user=> (.getClass (conj (cons 321321 [1]) 123123123))
clojure.lang.Cons
Note you are using [...] next!
user=> (.getClass [321312 1])
clojure.lang.PersistentVector
user=> (.getClass (conj [321312 1] 123123123))
clojure.lang.PersistentVector

Clojure idioms: sanely pass function-value pairs

Sometimes I want to pass argument-value pairs to a higher-order function, where the value I should pass is determined by the argument I pass. I want to be able to pass the argument without explicitly specifying the accompanying value. In particular, I'm interested in the case where the argument is itself a function.
Generic Example:
Here's a very generic example, where my-foo and my-bar are functions that I'm passing to higher-foo:
(higher-foo my-foo :option4 args) ;good
(higher-foo my-bar :option13 args) ;good
(higher-foo my-foo :option13 args) ;how stupid are you?! my-foo requires :option4!
Question: Is there a "standard" method for making :option4 or :option13 to be inferable by higher-foo so that I can just write (higher-foo my-foo) and (higher-foo my-bar)?
More Specific Example:
Bear in mind that there are better alternatives to the following code, but I'm just trying to put forward a concrete example of what I'm talking about:
(defn seq-has? [f n someseq]
(every? (partial apply f)
(partition n 1 someseq)))
(defn monotonicity [a b]
(<= a b))
(defn generalized-fib [a b c]
(= c (+ a b)))
(seq-has? monotonicity 2 someseq) should return true if the sequence is monotonic, false otherwise. (seq-has? generalized-fib 3 someseq) should return true if the sequence follows the generalized Fibonacci form, false otherwise.
But the "2" and "3" bother me. I could have an arbitrary number of properties to test for, and I don't want to have to remember the appropriate "magic numbers" for such calls.
Note: I know of two ways to do this, and for my own personal use, I suppose they both work. But I'm interested in what is idiomatic or considered best practice in the community. I'll post my answers, but I'm hoping there are more solutions.
Just make the predicate function itself take variadic arguments, and have it do the partitioning / recurring. Your monotonic? for instance already exists in core, and is called <=
(<= 1 2 4 5)
=> true
(<= 1 2 1 5)
=> false
Here's the source for the 1, 2 and variadic arg versions:
(source <=)
(defn <=
"Returns non-nil if nums are in monotonically non-decreasing order,
otherwise false."
{:inline (fn [x y] `(. clojure.lang.Numbers (lte ~x ~y)))
:inline-arities #{2}
:added "1.0"}
([x] true)
([x y] (. clojure.lang.Numbers (lte x y)))
([x y & more]
(if (<= x y)
(if (next more)
(recur y (first more) (next more))
(<= y (first more)))
false)))
You can make a fib? work the same way, have it take variadic arguments and recur over triples:
(defn fib?
[a b & [c & r]]
(if (= c (+ a b))
(if r
(recur b c r)
true)
false))
(fib? 0 1 1)
=> true
(fib? 2 3 5 8 13)
=> true
Since you are asking for a standard way how a function determines a not passed argument from one argument:
(defn f
([arg0] (case a :foo (f a :bar)
:baz (f a :quux)))
([arg0 arg1] ...))
Depending on your use case a different dispatch construct than case may be a better fit.
For your generic example this implies that higher-foo should determine the correct :option in the desired overload like demonstrated above.
In your specific example, you can't determine the n from the passed function. You need a more specific datastructure:
(defn seq-has? [{:keys [f n]} s]
(every? (partial apply f)
(partition n 1 s)))
(def monotonicity
{:f <=
:n 2})
(def generalized-fib
{:f #(= (+ %1 %2) %3)
:n 3})
(seq-has? monotonicity [1 2 3])
;; => true
This solution seems like a hack to me. Is it considered common/idiomatic? Use meta-data on the functions that define the property you are looking for:
(defn higher-foo [foo & args]
(apply foo (:option (meta foo))
args))
(def my-foo
(with-meta
(fn [a b] (println "I'm doing something cool"))
{:option :option4}))
;using it:
user=> (higher-foo my-foo arg)

Understanding Clojure concurrency example

I just go through various documentation on Clojure concurrency and came accross the example on the website (http://clojure.org/concurrent_programming).
(import '(java.util.concurrent Executors))
(defn test-stm [nitems nthreads niters]
(let [refs (map ref (replicate nitems 0))
pool (Executors/newFixedThreadPool nthreads)
tasks (map (fn [t]
(fn []
(dotimes [n niters]
(dosync
(doseq [r refs]
(alter r + 1 t))))))
(range nthreads))]
(doseq [future (.invokeAll pool tasks)]
(.get future))
(.shutdown pool)
(map deref refs)))
I understand what it does and how it works, but I don't get why the second anonymous function fn[] is needed?
Many thanks,
dusha.
P.S. Without this second fn [] I get NullPointerException.
Here is a classic example of using higher-order functions:
;; a function returns another function
(defn make-multiplyer [times]
(fn [x]
(* x times)))
;; now we bind returned function to a symbol to use it later
(def multiply-by-two (make-multiplyer 2))
;; let's use it
(multiply-by-two 100) ; => 200
In that code sample fn inside fn works the same way. When map invokes (fn [t] (fn [] ...)) it gets inner fn.
(def list-of-funcs (map (fn [t]
(fn [] (* t 10))) ; main part
(range 5)))
;; Nearly same as
;; (def list-of-funcs (list (fn [] (* 0 10))
;; (fn [] (* 1 10))
;; ...
;; (fn [] (* 4 10))))
(for [i list-of-funcs]
(i))
; => (0 10 20 30 40)
Update: And as Alex said tasks in the code sample is bound to list of callables which is passed then to .invokeAll().
The first fn is what map uses to create a seq of fn's -- one for each of the threads. This is because tasks is a seq of functions! The method .invokeAll() is expecting a Collection of Callables (Clojure functions implement the Callable interface)
from Clojure.org: Special Forms
fns implement the Java Callable, Runnable and Comparator interfaces.