首页 > 代码库 > [4Clojure]解题记录-#63
[4Clojure]解题记录-#63
题目
Difficulty: | Easy |
Topics: | core-functions |
Given a function f and a sequence s, write a function which returns a map. The keys should be the values of f applied to each item in s. The value at each key should be a vector of corresponding items in the order they appear in s.
1. (= (__ #(> % 5) [1 3 6 8]) {false [1 3], true [6 8]})
2. (= (__ #(apply / %) [[1 2] [2 4] [4 6] [3 6]]) {1/2 [[1 2] [2 4] [3 6]], 2/3 [[4 6]]})
3. (= (__ count [[1] [1 2] [3] [1 2 3] [2 3]]) {1 [[1] [3]], 2 [[1 2] [2 3]], 3 [[1 2 3]]})
限制:不能用“group-by”
题解:长度分61
(fn[f s](apply merge-with concat (map (fn [x] (hash-map (f x) [x])) s)))
中间过程测试:
1。生成hash-map:
user=> (map #(hash-map % 0) [1 2 3 4])
;({1 0} {2 0} {3 0} {4 0})
2. 测试merge-with
user=>(merge-with concat {false [1]} {false [2]} {true [3]} {true [4]})
;{true (3 4), false (1 2)}
3. 合并
user=>(merge-with concat (map #(hash-map ((fn[x](> x 5)) %) [%]) [1 2 3 4 5 6 7 8]))
;({false [1]} {false [2]} {false [3]} {false [4]} {false [5]} {true [6]} {true [7]} {true [8]})
有点问题,少了个东西
user=>(apply merge-with concat (map #(hash-map ((fn[x](> x 5)) %) [%]) [1 2 3 4 5 6 7 8]))
;{true (6 7 8), false (1 2 3 4 5)}
4. 整理成匿名函数,和题目要求的参数格式:
(fn[f s](apply merge-with concat (map (fn [x] (hash-map (f x) [x])) s)))
[4Clojure]解题记录-#63
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。