Clearing the map of her channels

Suppose we have a mapping mwith the following structure:

{:a (go "a") 
  :b "b" 
  :c "c" 
  :d (go "d")}

As shown, it mhas four keys, two of which contain channels.

Question . How to write a general function (or a macro?) cleanse-mapThat takes a type map mand displays its channel version (which would be in this case {:a "a" :b "b" :c "c" :d "d"})?

A good helper function for this question could be this:

(defn chan? [c]
  (= (type (chan)) (type c)))

It also doesn't matter if the return value cleanse-map(or whatever) is the channel itself. i.e:.

`(cleanse-map m) ;=> (go {:a "a" :b "b" :c "c" :d "d"})
+4
source share
2 answers

Limitations core.async cleanse-map . :

(defn cleanse-map [m]
  (let [entry-chs (map
                   (fn [[k v]]
                     (a/go
                       (if (chan? v)
                         [k (a/<! v)]
                         [k v])))
                   m)]
    (a/into {} (a/merge entry-chs))))

, :

  • , . , go -block .
  • merge -d . .
  • , ( a/into).
+3
(ns foo.bar
  (:require
    [clojure.core.async :refer [go go-loop <!]]
    [clojure.core.async.impl.protocols :as p]))

(def m
  {:a (go "a")
   :b "b"
   :c "c"
   :d (go "d")
   :e "e"
   :f "f"
   :g "g"
   :h "h"
   :i "i"
   :j "j"
   :k "k"
   :l "l"
   :m "m"})

(defn readable? [x]
  (satisfies? p/ReadPort x))

(defn cleanse-map
  "Takes from each channel value in m,
   returns a single channel which will supply the fully realized m."
  [m]
  (go-loop [acc {}
            [[k v :as kv] & remaining] (seq m)]
    (if kv
      (recur (assoc acc k (if (readable? v) (<! v) v)) remaining)
      acc)))

(go (prn "***" (<! (cleanse-map m))))

= > "***" {: m "m",: e "e",: l "l",: k "k",: g "g",: c "c",: j "j",: h "h",: b "b",: d "d",: f "f",: i "",: a "a" }

+1

All Articles