Skip to content

Instantly share code, notes, and snippets.

@BadUncleX
Last active April 11, 2018 02:31
Show Gist options
  • Save BadUncleX/e0042a3aa4d018edbad158f95bf099ec to your computer and use it in GitHub Desktop.
Save BadUncleX/e0042a3aa4d018edbad158f95bf099ec to your computer and use it in GitHub Desktop.
core.async hotdog

>! 基本用法

promise and deliver

(defn <!!
  "takes a val from port. Will return nil if closed. Will block
  if nothing is available."
  [port]
  (let [p (promise)
        ret (impl/take! port (fn-handler (fn [v] (deliver p v))))]
    (if ret
      @ret
      (deref p))))
;;
;; from https://www.braveclojure.com/core-async/
;;
(ns core-async-hotdog.10_hotdog_core_async_go_loop)
(require '[clojure.core.async :as async :refer [<! >! <!! >!! timeout chan alt! alts! alt!! alts!! close! go]])
;;
;; 投硬币, 吐出热狗
(defn hot-dog-machine
[]
(let [in (chan)
out (chan)]
(go (<! in)
(>! out "hot dog"))
[in out]))
(comment
(let [[in out] (hot-dog-machine)]
(>!! in "pocket lint")
(<!! out))
)
; => "hot dog"
;;
;; 对热狗机加以限制
;; 1. 限制总热狗数量
;; 2. 输入必须是3 元才吐出热狗
;;
(defn hot-dog-machine-v2
[hot-dog-count]
(let [in (chan)
out (chan)]
(go (loop [hc hot-dog-count]
;; 库存热狗数量大于0
(if (> hc 0)
(let [input (<! in)]
(if (= 3 input)
;; 输入恰好是3, 吐出热狗, 并且热狗数量减一
(do (>! out "hot dog")
(recur (dec hc)))
;; 不是3, 没有热狗, 返回继续循环
(do (>! out "wilted lettuce")
(recur hc))))
;; 库存热狗数量 <= 0, 关闭输入输出的channel
(do (close! in)
(close! out)))))
[in out]))
(comment
;; 共有3个热狗,可提交3次
(let [[in out] (hot-dog-machine-v2 3)]
(>!! in 3)
(println (<!! out))
(>!! in 2)
(println (<!! out))
(>!! in 3)
(println (<!! out))
(>!! in 3)
(println (<!! out))
(>!! in 3)
(println (<!! out)))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment