4clojure答案(一)

练习网址:http://www.4clojure.com/

一般是网上看到答案,然后不会api在下面的网址查。

API查询网址:http://clojuredocs.org/

英文文档:http://clojure-doc.org/

中文文档:https://code.google.com/archive/p/clojure-doc-en2ch/wikis

这个是用来调试debug的调试宏

(defmacro dbg[x] `(let [x# ~x] (println"dbg:" '~x"=" x#) x#))

不会哪里就用在哪里。

;; Examples of dbg
(println (+ (* 2 3 ) (dbg (* 8 9 ))))
(println (dbg (println"yo")))
(defn factorial[n] (if (= n 0 ) 1 (* n (dbg (factorial (dec n))))))
(factorial 8 )

(def integers (iterate inc 0 ))
(def squares (map #(dbg(* % %)) integers))
(def cubes (map #(dbg(* %1 %2)) integers squares))
(take 5 cubes)
(take 5 cubes)
另外4clojure上也有不少用户的精彩回答,不妨研究一下(关注其他用户可看其答案)
#1 Nothing but the Truth

(= true true)

#2 Simple Math

(= (- 10 (* 2 3)) 4)

#3 Intro to Strings

(= "HELLO WORLD" (.toUpperCase "hello world"))

#4 Intro to Lists

(= (list:a :b :c) '(:a :b :c))

#5  Lists: conj

(= '(1 2 3 4) (conj '(2 3 4) 1))

#6 Intro to Vectors

(= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c))

#7 Vectors: conj

(= [1 2 3 4] (conj [1 2 3] 4))

#8 Intro to Sets

(= #{:a :b :c :d} (set '(:a :a :b :c :c :c :c :d :d)))

#9 Sets: conj

(= #{1 2 3 4} (conj #{1 4 3} 2))

#10 Intro to Maps

(= 20 ((hash-map :a 10, :b 20, :c 30) :b))

(= 20 ((hash-map :a 10, :b 20, :c 30) :b))

#11 Maps: conj

(= {:a 1, :b 2, :c 3} (conj {:a 1} [:b 2][:c 3]))

#12 Intro to Sequences

(= 3 (first '(3 2 1)))

#13 Sequences: rest

(= '(20 30 40) (rest [10 20 30 40]))

#14 Intro to Functions

(= 8 ((fn add-five [x] (+ x 5)) 3))
(= 8 ((fn [x] (+ x 5)) 3))
(= 8 (#(+ % 5) 3))
(= 8 ((partial + 5) 3))

#15 Double Down

(= ((fn [x] (* x 2)) 2) 4)
(= (* 2 3) 6)
(= ((partial * 2) 11) 22)
(= (#(* % 2) 7) 14)

#16 Hello World

(= ((fn [n] (str "Hello, " n "!")) "Dave") "Hello, Dave!")
(= (#(str "Hello, " % "!") "Jenn") "Hello, Jenn!")
(= (#(str "Hello, " % "!")  "Rhea") "Hello, Rhea!")

#17 Sequences: map

(= '(6 7 8) (map #(+ % 5) '(1 2 3)))

#18 Sequences: filter

(= '(6 7) (filter #(> % 5) '(3 4 5 6 7)))

#19 Last Element

(= (#(first (reverse %)) [1 2 3 4 5]) 5)

(= ((comp first reverse)  '(5 4 3)) 3)
(= (#(nth % (dec (count %))) ["b" "c" "d"]) "d")

#20 Penultimate Element

(= (#(first (rest (reverse %))) (list 1 2 3 4 5)) 4)
(= (#(second (reverse %)) ["a" "b" "c"]) "b")
(= (#(->% reverse rest first) [[1 2] [3 4]]) [1 2])

#21 Nth Element

(= (#(first (drop %2 %1)) '(4 5 6 7) 2) 6)
(= (#((vec %1) %2) [:a :b :c] 0) :a)
(= (#(->> %1 (drop %2) first) [1 2 3 4] 1) 2)
(= (#(loop [x %1 y %2] (if (zero? y) (first x) (recur (rest x) (dec y)))) '([1 2] [3 4] [5 6]) 2) [5 6])

drop

(drop n) (drop n coll)

Returns a lazy sequence of all but the first n items in coll.
Returns a stateful transducer when no collection is provided.

vec

(vec coll)
Creates a new vector containing the contents of coll. Java arrays will be aliased and should not be modified.

#22 Count a Sequence

(= (#(reduce (fn [x y] (inc x)) 0 %) '(1 2 3 3 1)) 5)
(= (reduce (fn [c _] (inc c)) 0 "Hello World") 11)
(= ((fn [sequence] (reduce (fn [acc v] (inc acc)) 0 sequence)) [[1 2] [3 4] [5 6]]) 3)
(= ((fn foo [s] (if (empty? s) 0 (+ 1 (foo (rest s))))) '(13)) 1)
(= (#(loop [result 0 c %]
(if(empty? c) result
(recur (inc result) (rest c)))) '(:a :b :c)) 3)

#23 Reverse a Sequence

(= (#(into () %) [1 2 3 4 5]) [5 4 3 2 1])
(= (reduce conj () (sorted-set 5 7 2 7)) '(7 5 2))
(= (apply conj ()  [[1 2][3 4][5 6]]) [[5 6][3 4][1 2]])

#24 Sum It All Up

(= (reduce + [1 2 3]) 6)
(= (apply + (list 0 -2 5 5)) 8)
(= (#(apply + %) #{4 2 1}) 7)
(= (reduce #(+ %1 %2) '(0 0 -1)) -1)
(= (reduce + '(1 10 3)) 14)

#25 Find the odd numbers

(= (#(filter odd? %) #{1 2 3 4 5}) '(1 3 5))
(= (filter odd? [4 2 1 6]) '(1))
(= (filter #(= 1 (rem % 2)) [2 2 4 6]) '())
(= (filter #(== (mod % 2) 1) [1 1 1 3]) '(1 1 1 3))

#26 Fibonacci Sequence

(= (#(take % (map last

(iterate (fn [[x y]]

[y (+ x y)])

[ 0 1]))) 8)

'(1 1 2 3 5 8 13 21))

#27 Palindrome Detector

(false? (#(= (seq %) (reverse %)) '(1 2 3 4 5)))
(true? ((fn [xs] (= (seq xs) (reverse xs))) "racecar"))
(true? ((fn [x] (= (clojure.string/join x) (clojure.string/join (reverse x)))) [:foo :bar :foo]))
(true? (#(if (= (apply str %) (apply str (vec (reverse %)))) true false) '(1 1 3 3 1 1)))
(false? (#(
if(< (count %1)3)
true
(if(=(first %1)(last %1))
(recur (-> %1 rest butlast))
false)
) '(:a :b :c)))

#28 Flatten a Sequence

(= (#(filter (complement sequential?)
(rest (tree-seq sequential? seq %))) '((1 2) 3 [4 [5 6]])) '(1 2 3 4 5 6))
(= (#(filter (complement sequential?) (tree-seq sequential? identity %)) ["a" ["b"] "c"]) '("a" "b" "c"))
(= ((fn myFlatten [x]
(if (coll? x)
(mapcat myFlatten x)
[x])) '((((:a))))) '(:a))

#29  Get the Caps

(= (#(apply str (re-seq #"[A-Z]" %)) "HeLlO, WoRlD!") "HLOWRD")
(empty? (#(clojure.string/replace % #"[^A-Z]+" "") "nothing"))
(= (#(apply str (filter (set (map char (range 65 91))) %)) "$#A(*&987Zf") "AZ")

#30 Compress a Sequence

(= (apply str (__ "Leeeeeerrroyyy")) "Leroy")
(= (__ [1 1 2 3 3 2 2 3]) '(1 2 3 2 3))
(= (__ [[1 2] [1 2] [3 4] [1 2]]) '([1 2] [3 4] [1 2]))

;;第一种方法

(fn [input]
(loop [i input res []]
(if (empty? i)
res
(if (= (last res) (first i))
(recur (rest i) res)
(recur (rest i) (conj res (first i))))
)))

;;或者

#(map first (partition-by identity %))

#31 Pack a Sequence

(= (__ [1 1 2 1 1 1 3 3]) '((1 1) (2) (1 1 1) (3 3)))
(= (__ [:a :a :b :b :c]) '((:a :a) (:b :b) (:c)))
(= (__ [[1 2] [1 2] [3 4]]) '(([1 2] [1 2]) ([3 4])))

#(partition-by identity %)

(fn [coll] (partition-by identity coll))

#32 Duplicate a Sequence

(= (__ [1 2 3]) '(1 1 2 2 3 3))
(= (__ [:a :a :b :b]) '(:a :a :a :a :b :b :b :b))
(= (__ [[1 2] [3 4]]) '([1 2] [1 2] [3 4] [3 4]))
(= (__ [[1 2] [3 4]]) '([1 2] [1 2] [3 4] [3 4]))

#(mapcat (partial repeat 2) %)

#(sort (into % %))

reduce #(conj %1 %2 %2) []

#(interleave % %)

mapcat #(list % %)

 

interleave
clojure.core

(interleave)(interleave c1)(interleave c1 c2)(interleave c1 c2 & colls)
Returns a lazy seq of the first item in each coll, then the second etc.

into
clojure.core

(into)(into to)(into to from)(into to xform from)
Returns a new coll consisting of to-coll with all of the items of
from-coll conjoined. A transducer may be supplied.

sort
clojure.core

(sort coll)(sort comp coll)
Returns a sorted sequence of the items in coll. If no comparator is
supplied, uses compare. comparator must implement
java.util.Comparator. Guaranteed to be stable: equal elements will
not be reordered. If coll is a Java array, it will be modified. To
avoid this, sort a copy of the array.

mapcat
clojure.core

(mapcat f)(mapcat f & colls)
Returns the result of applying concat to the result of applying map
to f and colls. Thus function f should return a collection. Returns
a transducer when no collections are provided

#33 Replicate a Sequence

(= (__ [1 2 3] 2) '(1 1 2 2 3 3))
(= (__ [:a :b] 4) '(:a :a :a :a :b :b :b :b))
(= (__ [4 5 6] 1) '(4 5 6))
(= (__ [[1 2] [3 4]] 2) '([1 2] [1 2] [3 4] [3 4]))
(= (__ [44 33] 2) [44 44 33 33])

基本和上面题目很相似

#(mapcat (partial repeat %2) %)

#34 Implement range

 

(= (__ 1 4) '(1 2 3))
(= (__ -2 2) '(-2 -1 0 1))
(= (__ 5 8) '(5 6 7))

#(take (- %2 %1) (iterate inc %1))

take
clojure.core

(take n)(take n coll)
Returns a lazy sequence of the first n items in coll, or all items if
there are fewer than n. Returns a stateful transducer when
no collection is provided.

;; return a lazy seq of the first 3 items
(take 3 '(1 2 3 4 5 6))
;;=> (1 2 3)

#35 Local bindings

(= 7 (let [x 5] (+ 2 x)))
(=7 (let [x 3, y 10] (- y x)))
(= 7 (let [x 21] (let [y 3] (/ x y))))

let
clojure.core

(let [bindings*] exprs*)
binding => binding-form init-expr
Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein.

36 Let it Be

(= 10 (let __ (+ x y)))
(= 4 (let __ (+ y z)))
(= 1 (let __ z))

[x 7 y 3 z 1]

#37 Regular Expressions

(= "ABC" (apply str (re-seq #"[A-Z]+" "bA1B3Ce ")))

#38 Maximum value

(= (__ 1 8 3 4) 8)
(= (__ 30 20) 30)
(= (__ 45 67 11) 67)

#(last (sort %&))

(fn [& x] (reduce (fn [y z] (if (< y z) z y)) 0 (seq x)))

seq

(seq coll)
Returns a seq on the collection. If the collection is
empty, returns nil. (seq nil) returns nil. seq also works on
Strings, native Java arrays (of reference types) and any objects
that implement Iterable. Note that seqs cache values, thus seq
should not be used on any Iterable whose iterator repeatedly
returns the same mutable object.

(seq '(1))  ;;=> (1)
(seq [1 2]) ;;=> (1 2)
(seq "abc") ;;=> (\a \b \c)

;; Corner cases
(seq nil)   ;;=> nil
(seq '())   ;;=> nil
(seq "")    ;;=> nil
#39 Interleave Two Seqs

(= (__ [1 2 3] [:a :b :c]) '(1 :a 2 :b 3 :c))
(= (__ [1 2] [3 4 5 6]) '(1 3 2 4))
(= (__ [1 2 3 4] [5]) [1 5])
(= (__ [30 20] [25 15]) [30 25 20 15])

#(flatten (map vector %1 %2))

mapcat list

mapcat vector

flatten
clojure.core

(flatten x)
Takes any nested combination of sequential things (lists, vectors,
etc.) and returns their contents as a single, flat sequence.
(flatten nil) returns an empty sequence.

user=> (flatten [1 [2 3]])
(1 2 3)

user=> (flatten '(1 2 3))
(1 2 3)

user=> (flatten '(1 2 [3 (4 5)])) 
(1 2 3 4 5)

user=> (flatten nil)
()

; Attention with stuff which is not a sequence

user=> (flatten 5)
()

user=> (flatten {:name "Hubert" :age 23})
()

; Workaround for maps

user=> (flatten (seq {:name "Hubert" :age 23}))
(:name "Hubert" :age 23)

vector
clojure.core

(vector)(vector a)(vector a b)(vector a b c)(vector a b c d)(vector a b c d e)(vector a b c d e f)(vector a b c d e f & args)
Creates a new vector containing the args.

#40 Interpose a Seq

(= (__ 0 [1 2 3]) [1 0 2 0 3])
(= (apply str (__ ", " ["one" "two" "three"])) "one, two, three")
(= (__ :z [:a :b :c :d]) [:a :z :b :z :c :z :d])

#(rest (interleave [% % % %] %2))

#(rest (interleave (repeat (count %2) %1) %2))

#(drop-last (interleave %2 (repeat %1)))

#(butlast (interleave %2 (repeat %1)))

drop-last
clojure.core

(drop-last s)(drop-last n s)
Return a lazy sequence of all but the last n (default 1) items in coll

user=> (drop-last [1 2 3 4])
(1 2 3) 

user=> (drop-last -1 [1 2 3 4])
(1 2 3 4) 

user=> (drop-last 0 [1 2 3 4])
(1 2 3 4) 

user=> (drop-last 2 [1 2 3 4])
(1 2)

user=> (drop-last 5 [1 2 3 4])
()

butlast
clojure.core

(butlast coll)
Return a seq of all but the last item in coll, in linear time

user=> (butlast [1 2 3])
(1 2)
user=> (butlast (butlast [1 2 3]))
(1)
user=> (butlast (butlast (butlast [1 2 3])))
nil
#41

#(apply concat (partition-all (dec %2) %2 %))

#42

#(apply * (range 1 (+ % 1)))

#(reduce * (range 1 (inc %)))

#43

(fn [s c]
(partition (/ (count s) c) (apply interleave (partition c s))))

#(apply map list (partition %2 %1))

#44

Solutions:
#(take (count %2)
(drop (mod % (count %2))
(cycle %2)))

#(let [rot (mod %1 (count %2))]
(concat (drop rot %2) (take rot %2)))

#45

'(1 4 7 10 13)

(take 5 (iterate #(+ 3 %) 1))

#46

(fn [f] #( f %2 %))

#(fn [x y] (% y x))

#47

4

#48

6

#49

(juxt take drop)

(fn [n s] [(take n s) (drop n s)])

juxt
clojure.core

(juxt f)(juxt f g)(juxt f g h)(juxt f g h & fs)
Takes a set of functions and returns a fn that is the juxtaposition
of those fns. The returned fn takes a variable number of args, and
returns a vector containing the result of applying each fn to the
args (left-to-right).
((juxt a b c) x) => [(a x) (b x) (c x)]

((juxt + * min max) 3 4 6)
;;=> [13 72 3 6]

#50

#(vals(group-by type%))

vals
clojure.core

Available since 1.0 (source)
(vals map)
Returns a sequence of the map's values, in the same order as (seq map).

(vals {:a "foo", :b "bar"})
;;=> ("foo" "bar")

type
clojure.core

Available since 1.0 (source)
(type x)
Returns the :type metadata of x, or its Class if none

;; Checking numbers
user=> (type 10)
java.lang.Long

user=> (type 10.0)
java.lang.Double
#51

[1 2 3 4 5]

#52

[c e]

#53 Longest Increasing Sub-Seq

(= (__ [1 0 1 2 3 0 4 5]) [0 1 2 3])
(= (__ [5 6 1 3 2 7]) [5 6])
(= (__ [2 3 3 4 5]) [3 4 5])
(= (__ [7 6 5 4]) [])

#(apply max-key %
(reverse
(for [x (%2 (% %3)) % (%2 x (- (% %3) 1))
:let [% (subvec %3 x (+ % 2))]]
(if (apply < %) % []))))
count range

(fn [s]
(->>
(for [a (range (count s))
b (range (inc a) (count s))]
(subvec s a (inc b)))
(filter #(apply < %))
(sort-by count >)
first
vec))

max-key
clojure.core

Available since 1.0 (source)
(max-key k x)(max-key k x y)(max-key k x y & more)
Returns the x for which (k x), a number, is greatest.

subvec

(subvec v start)(subvec v start end)
Returns a persistent vector of the items in vector from
start (inclusive) to end (exclusive). If end is not supplied,
defaults to (count vector). This operation is O(1) and very fast, as
the resulting vector shares structure with the original and no
trimming is done.

;; not supplying 'end' returns vector from 'start' to (count vector)
user=> (subvec [1 2 3 4 5 6 7] 2)
[3 4 5 6 7]

;; supplying 'end' returns vector from 'start' to element (- end 1)
user=> (subvec [1 2 3 4 5 6 7] 2 4)
[3 4]
#54 Partition a Sequence

(= (__ 3 (range 9)) '((0 1 2) (3 4 5) (6 7 8)))
(= (__ 2 (range 8)) '((0 1) (2 3) (4 5) (6 7)))
(= (__ 3 (range 8)) '((0 1 2) (3 4 5)))

#(map (fn [x] (take % (drop (* % x) %2)))
(range (quot (count %2) %)))

(fn my-partition [n v]
(if (>= (count v) n)
(cons (take n v) (my-partition n (drop n v)))))

cons
clojure.core

Available since 1.0 (source)
(cons x seq)
Returns a new seq where x is the first element and seq is
the rest.

;; prepend 1 to a list
(cons 1 '(2 3 4 5 6))
;;=> (1 2 3 4 5 6)
user=> (cons 3 '(2 3 4 5 6))
(3 2 3 4 5 6)

;; notice that the first item is not expanded
(cons [1 2] [4 5 6])
;;=> ([1 2] 4 5 6)
#55 Count Occurrences

(= (__ [1 1 2 3 2 1 1]) {1 4, 2 2, 3 1})
(= (__ [:b :a :b :a :b]) {:a 2, :b 3})
(= (__ '([1 2] [1 3] [1 3])) {[1 2] 1, [1 3] 2})

reduce #(assoc % %2(+ (% %2 0) 1)) {}

assoc
clojure.core

Available since 1.0 (source)
(assoc map key val)(assoc map key val & kvs)
assoc[iate]. When applied to a map, returns a new map of the
same (hashed/sorted) type, that contains the mapping of key(s) to
val(s). When applied to a vector, returns a new vector that

(assoc [1 2 3] 0 10)     ;;=> [10 2 3]
(assoc [1 2 3] 3 10)     ;;=> [1 2 3 10]
(assoc [1 2 3] 2 '(4 6)) ;;=> [1 2 (4 6)]
#56

(fn f [a [x & r]]
(if x (f (if ((set a) x) a (conj a x)) r) a))
[]

#(sort-by (fn [i] (.indexOf % i)) (map first (group-by identity %)))

reduce #(if ((set %) %2) % (conj % %2)) []

#57

[5 4 3 2 1]

'(5 4 3 2 1)

#58

(fn [& xs] (fn [& ys] (reduce #(%2 %1) (apply (last xs) ys) (rest (reverse xs)))))

(fn [& f]
#((reduce (fn [v f] [(apply f v)]) %& (reverse f)) 0))

#59

(defn foo59 [& f]
(fn [& a]
(map #(apply % a) f)))
(= [21 6 1] ((foo59 + max min) 2 3 5 1 6 4))
(= ["HELLO" 5] ((foo59 #(.toUpperCase %) count) "hello"))
(= [2 6 4] ((foo59 :a :c :b) {:a 2, :b 4, :c 6, :d 8 :e 10}))

#60

(= (take 5 ((fn r ([f v s]
(lazy-seq
(cons v
(if (seq s)
(r f (f v (first s)) (rest s))))))
([f s] (r f (first s) (rest s)))) + (range))) [0 1 3 6 10])
(= ((fn r ([f v s]
(lazy-seq
(cons v
(if (seq s)
(r f (f v (first s)) (rest s))))))
([f s] (r f (first s) (rest s)))) conj [1] [2 3 4]) [[1] [1 2] [1 2 3] [1 2 3 4]])
(= (last ((fn r ([f v s]
(lazy-seq
(cons v
(if (seq s)
(r f (f v (first s)) (rest s))))))
([f s] (r f (first s) (rest s)))) * 2 [3 4 5])) (reduce * 2 [3 4 5]) 120)

#61

(= (__ [:a :b :c] [1 2 3]) {:a 1, :b 2, :c 3})
(= (__ [1 2 3 4] ["one" "two" "three"]) {1 "one", 2 "two", 3 "three"})
(= (__ [:foo :bar] ["foo" "bar" "baz"]) {:foo "foo", :bar "bar"})

#(apply hash-map (mapcat list % %2))

#(apply hash-map (interleave %1 %2))

 

4clojure答案(二): https://okayjam.com/index.php/2017/04/26/4clojure答案(二)/

 

发表回复

您的电子邮箱地址不会被公开。

粤ICP备17041560号-2