Clojure: apply vs reduce for converting integers to chars and strings -
both of below functions return same output, first 1 uses reduce , pair of quote marks achieve same thing. played code , if delete ""
marks, first character in sequence not converted it's integer value. second 1 seems clear me, feel first way superior, because packages of desired effects single function literal. unpack anonymous function me explain variables %
, %2
referring , tell me why need ""
first integer (115
) in vector?
(reduce #(str % (char %2)) "" [115 101 99 114 101 116 32 109 101 115 115 97 103 101 115]) (apply str (map #(char %) [115 101 99 114 101 116 32 109 101 115 115 97 103 101 115]))
the first function taken clojure cookbook discussion on int
str
conversion, here.
you can find anonymous function reader macro here
anonymous function literal (#())
#(...) => (fn [args] (...))
where args determined presence of argument literals taking form %, %n or %&. % synonym %1, %n designates nth arg (1-based), , %& designates rest arg. not replacement fn - idiomatic used short one-off mapping/filter fns , like. #() forms cannot nested.
%
or %1
refers first argument , %2
refers second.
in case, in first approach, %
refers ""
, %2
refers vector of integers; in second approach, %
vector of integers.
as difference between reduce
, apply
here, reduce
provides supplied val
, , in case ""
. without ""
, reduce
call str
115
, (char 101)
, produce "115e"
. instead of calling str
first , second element in vector, should call str
empty string , first element of vector, produce "s"
. , in next reduce loop, str
called parameter "s"
, 101
, yielding "se"
, , on.
and apply
call, you've mapped char
vector of integer before call apply
, parameter of apply
be: 1. function str
; 2.a vector of characters function map
produced.
also, can check out more information differences between apply
, reduce
in this question.
Comments
Post a Comment