Apply list of function to a seq in clojure - clojure

I have a list of function, e.g [f g h ..] and list items with the same length [a b c ..].
What's proper way to get result as: [(f a) (g b) (h c) ..] (apply each function to an item at the same position)

Related

How do I partition a list into (sub-)lists of random length?

Input, by example (4 is the maximum length):
(my-partition-randomly '(a b c d e f g h i j k l) 4)
Output:
'((a b c) (d) (e f g h) (i j k) (l))
The code should run in the Emacs Lisp interpreter.
My elisp-fu is weak, but I was able to write the following function:
(defun my-partition-randomly (list max-length) ""
(let ((result '()))
(while list
(push (seq-take-while (lambda (x) x)
(map 'list
(lambda (x) (pop list))
(number-sequence 1 (+ 1 (random max-length)))))
result))
(reverse result)))
It extracts random initial sequences of the input list and adds them to result (the seq-take-while is needed not to include nils when the last subsequence wants to be longer than the remaining list). push adds elements to the left, so the result has to reversed.

How do I accumulate repeated application of a function to a list of values?

How do I accumulate the successive application of a function to a list of values in Haskell?
I'm not sure I'm phrasing that right, but what I'm looking for, for example, is that I have a list values of type X,
l = [a, b, c, d, e]
and a function
f :: X -> X -> X
and I want
(f e (f d (f c (f b a))))
which I think can perhaps be expressed with $ somehow.
I see that Haskell has some fold functions, but I can't quite figure out how to get it to work like the fold operations I'm familiar with.
Isn't this just foldl1 (flip f) l? You want a left fold, and you want the operation to start with the first item in the list rather than a specific accumulator.
Well, your function f really has type:
f :: X -> X -> X
Then the expression you are interested in is:
foldr1 f [e, d, c, a, b] -- note the twist at the end.
If you want to compute:
f e (f d (f c (f b a))) -- note last term is: f b a
then it is just:
foldr1 f [e, d, c, b, a]
Play with simple-reflect to figure it out.
ghci> import Debug.SimpleReflect
ghci> foldl1 f [a,b,c,d,e]
f (f (f (f a b) c) d) e
ghci> foldl (flip f) z [a,b,c,d,e]
f e (f d (f c (f b (f a z))))
And so on...

Sequentially nest vectors/list in Clojure?

How could I convert this:
[a b c d e]
or this:
(e d c b a) ;(rseq [a b c d e])
to this:
[a[b[c[d[e]]]]]
I've been wracking my brain and I feel like there is a simple solution! :-\
Ultimately I want to do this:
[a b c d e]
[a b c x y]
[a b c d j k]
as this:
{a {b {c {d {e}
{j {k}}
{x {y}}}}
Which I think conj will help with
(Update: added answer to the new question added in the edit below the answer to the original question.)
I've actually answered this very question in #clojure recently.
Here are two approaches: f is pretty much the spec directly transformed into code, which however creates a seq -- (next xs) -- which immediately gets poured into a new vector at each step; g is a much better version which only allocates objects which will actually occur in the output, plus a vector and the seq links to traverse it:
;; [1 2 3] -> [1 [2 [3]]]
;; naive, quadratic:
(defn f [xs]
(if (next xs)
[(first xs) (vec (f (next xs)))]
(vec xs)))
;; only allocates output + 1 vector + a linear number of seq links,
;; linear overall:
(defn g [v]
(reduce (fn [acc x]
[x acc])
[(peek v)]
(rseq (pop v))))
NB. I'm overlooking the usual logarithmic factors arising from vector operations (so this is soft-O complexity).
As for producing a nested map, the above isn't particularly useful. Here's one approach:
(defn h
([v]
(h nil v))
([m v]
(assoc-in m v nil)))
(h [1 2 3 4])
;= {1 {2 {3 {4 nil}}}}
(def data
'[[a b c d e]
[a b c x y]
[a b c d j k]])
(reduce h {} data)
;= {a {b {c {x {y nil}, d {j {k nil}, e nil}}}}}
I'm using nil as a "terminator", since {y} (as currently found in the answer text) is not a well-formed literal. true might be a more convenient choice if you plan to call these maps as functions to check for presence of keys.
Simpler solution here (using destructuring and non-tail recursion):
http://ideone.com/qchXZC
(defn wrap
([[a & as]]
(if-let [[b & cs] as]
[a (wrap as)]
[a])))

Clojure - indexing a sequence without using nexts

New to Clojure and trying to figure out how to index a sequence without using lots of nexts. For instance say I have the sequence:
(a b c d e f g h)
and I want to incorporate into a function the returning of the 4th item of the sequence. There must be some way besides (next (next (next sequence_name)))? So I could just pass the number 4 to the function (or any other number) and get that item from the sequence. Thanks!
A few different ways:
(take 1 (drop 3 '(a b c d e f g h))) ;; d
(nth '(a b c d e f g h) 3) ;; d
(nth [a b c d e f g h] 3) ;; d
(nth (vec '(a b c d e f g h)) 3) ;;d
I recommend you become familiar with the sequence manipulation functions in the Clojure Cheat Sheet - it's totally worth it. Clojure's sequence library is extremely rich.
good old nth should do the trick
user> (nth '(a b c d e f g h) 4)
e
(that is indexed from 0 of course)

applying list of functions to list in common lisp

I have a list of functions, a list of elements, and I'd like to apply all the functions on all the elements then append all the resulting lists together. I did it as follow
(defun apply-functions(funcs elements)
(if (null funcs)
nil
(append (mapcar #'(lambda (x) (funcall (car funcs) x)) elements) (apply-functions (rest funcs) elements))))
It works as intended, but I don't like it. Is there a cleaner, more concise way of doing it?. I am new to lisp, and still getting used to the lispish style of doing things.
I don't know if you like loop macro (and I don't want to spoil anyone), but try this:
(defun apply-functions (fs es)
(loop for f in fs appending (mapcar f es)))
This is the same idea as yours, just shorter:
(defun apply-functions (functions elements)
(mapcan #'(lambda (x) (mapcar x elements)) functions))
I would define a function, call-each that returns a new function,
returning the list of calling each function on it's argument:
(defun call-each (fns)
(lambda (arg)
(mapcar (lambda (fn)
(funcall fn arg))
fns)))
(funcall (call-each (list #'third #'second #'first)) '(a b c))
;=> (C B A)
cl has the function mapcan which is basically nconc + mapcar :
(mapcan #'reverse '((a b c)
(e f g)
(h i j)))
;=> (C B A G F E J I H)
(mapcan (call-each (list #'identity #'1+)) '(1 3 5 7 9))
;=> (1 2 3 4 5 6 7 8 9 10)
unfortunately, nconc, which mapcan uses, is destructive:
(let ((data '((a b c)
(d e f)
(g h i))))
;;here be dragons
(list (mapcan #'identity data)
data))
;=> ((A B C D E F G H I) ((A B C D E F G H I) (D E F G H I) (G H I)))
alexandria to the rescue:
(let ((data '((a b c)
(d e f)
(g h i))))
;;safe version
(list (alexandria:mappend #'identity data)
data))
;=> ((A B C D E F G H I) ((A B C) (D E F) (G H I)))
note that using mapcan is more efficient, but unless you know exactly where
your data is coming from, and who owns it, mappend is the way to go.
so you could write:
(defun apply-functions (fs es)
(when fs
(alexandria:mappend (call-each fs) es))
(apply-functions (list #'identity #'1+) '(1 3 5 7 9))
;=> (1 2 3 4 5 6 7 8 9 10)