Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2020
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns saikyun.mein.collections
  2.   #?(:cljs (:require [alc.x-as-tests.cljs.immediate :refer-macros [run-tests!]])
  3.      :clj  (:require [alc.x-as-tests.immediate :refer [run-tests!]])))
  4.  
  5. (defn fconj
  6.   ([c v] (fconj c v []))
  7.   ([c v kind]
  8.    (cond (nil? c)
  9.          (conj kind v)
  10.          
  11.          (coll? c)
  12.          (into kind (conj c v))
  13.          
  14.          :else
  15.          (conj kind c v))))
  16.  
  17. (comment
  18.   ;; turns two non-coll values into collection
  19.   (fconj 1 2)     ;;=> [1 2]
  20.   (fconj 1 [2])   ;;=> [1 [2]]
  21.   (fconj 1 2 #{}) ;;=> #{1 2}
  22.  
  23.   ;; turns collection and value into that collection
  24.   (fconj [1 2] 3)   ;;=> [1 2 3]
  25.   (fconj [1 2] [3]) ;;=> [1 2 [3]]
  26.  
  27.   ;; nil and value returns coll with value as only element
  28.   (fconj nil 2)   ;;=> [2]
  29.   )
  30.  
  31. (defn fmap
  32.   [f v]
  33.   (cond (nil? v) v
  34.        
  35.         (coll? v)
  36.         (map f v)
  37.        
  38.         :else
  39.         (f v)))
  40.  
  41. (defn fmap!
  42.   [f v]
  43.   (cond (nil? v) v
  44.        
  45.         (or (coll? v)
  46.             #?(:cljs (.isArray js/Array v)))
  47.         (doall (map f v))
  48.        
  49.         :else
  50.         (f v)))
  51.  
  52. (comment
  53.   ;; works on values
  54.   (fmap inc 1)
  55.   ;;=> 2
  56.  
  57.   ;; works on collections
  58.   (fmap inc [1 2 3])
  59.   ;;=> [2 3 4]
  60.  
  61.   (fmap inc '(1 2 3))
  62.   ;;=> [2 3 4]
  63.  
  64.   (->> (fmap #(update % 1 inc) '{:a 10, :b 20})
  65.        (into {}))
  66.   ;;=> {:a 11, :b 21}
  67.   )
  68.  
  69. (run-tests!)
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement