[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)))

转载于:https://www.cnblogs.com/zjfu/p/4124731.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值