Skip to content

Instantly share code, notes, and snippets.

@visibletrap
Last active August 5, 2016 06:25
Show Gist options
  • Save visibletrap/7d5f7c59bf0f819a463710b2b6899621 to your computer and use it in GitHub Desktop.
Save visibletrap/7d5f7c59bf0f819a463710b2b6899621 to your computer and use it in GitHub Desktop.
(def I (atom {:inventory1 1000 :inventory2 0})) ; สร้าง atom ที่เก็บ map ของ inventories แล้ว bind ไว้ที่ Var I
@I
=> {:inventory1 1000, :inventory2 0} ; deref ดูค่า atom I ในปัจจุบัน
; ประกาศฟังก์ชัน move-amount รับ 4 อาร์กิวเม้น inventories, from-key, to-key, n
(defn move-amount [inventories from-key to-key n]
(let [from-val (get inventories from-key) ; ใช้ค่าจาก from-key ที่เป็น keyword ไปดึงค่าออกจาก inventories ซึ่งเป็น map bind ไว้ที่ from-val
to-val (get inventories to-key)] ; ดึงค่าออกจาก map ด้วย to-key bind ไว้ที่ to-val
(assoc inventories from-key (- from-val n) ; ใส่ค่ากลับไปที่ inventories โดยใช้ from-key เป็น key ส่วน value คือ from-val - n
to-key (+ to-val n)))) ; ใส่อีกคู่นึงกลับไปที่ map โดยใช้ to-key เป็น key ส่วน value คือ to-val + n
; วนลูป 100 รอบ ไม่สนเลขในแต่ละรอบ
(doseq [_ (range 0 100)]
(future (swap! I move-amount :inventory1 :inventory2 1)))
; สร้าง thread ใหม่ที่ไปแก้ค่า I โดยส่งฟังก์ชัน move-amount พร้อมอาร์กิวเม้นอีก 3 ตัวเข้าไป
; อาร์กิวเม้นอีกตัว(ตัวแรกของ move-amount)ได้มาจากสิ่งที่อยู่ใน I อยู่แล้ว
@I ; deref ดูค่าภายใน I หลังจาก threads ทำงานกันเสร็จ
=> {:inventory1 900, :inventory2 100}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment