4clojure第50个问题根据类型拆分序列

;Split by Type
 
;Difficulty:	Medium
;Topics:	seqs

;Write a function which takes a sequence consisting of items with different types and splits them up into a set of homogeneous sub-sequences. The internal order of each sub-sequence should be maintained, but the sub-sequences themselves can be returned in any order (this is why 'set' is used in the test cases).
	
;(= (set (__ [1 :a 2 :b 3 :c])) #{[1 2 3] [:a :b :c]})
	
;(= (set (__ [:a "foo"  "bar" :b])) #{[:a :b] ["foo" "bar"]})
	
;(= (set (__ [[1 2] :a [3 4] 5 6 :b])) #{[[1 2] [3 4]] [:a :b] [5 6]})
(ns for-clojure.problem50)


(defn split-by-type [v]
  (loop [r {} 
         v v]
    (if (empty? v) 
      (map val r)
      (let [ele (first v)
            ele-type (type ele)]
        (if (get r ele-type)
          (recur (update-in r [ele-type] conj ele) (rest v))
          (recur (assoc r ele-type [ele]) (rest v)))))))

(split-by-type [1 :a 2 :b 3 :c])


我的答案相对复杂。主要原因是对这里涉及到的函数不是很熟悉
vals就完成了我(map val)的功能
在问题之初,我想用类似partition-by的功能实现,但是partition-by会依次对序列进行判断,下一个与上一个不相同的时候,就放入到一个新的子序列中,因此相同的判断的元素可能不在同一个子序列中。
其实group-by函数才是我需要的函数
所以最简单的答案应该是 #(vals (group-by type %))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值