clojure union between object - object

How I can do special merge like this: (Where special-merge a function, received two object, return an object)
(def tab-a [
{:c '({:v 60} {:v nil})}
{:c '({:v 70} {:v 66})}
])
(def tab-b [
{:c '({:v 40} {:v 11})}
{:c '({:v 70} {:v 22})}
])
(special-merge tab-a tab-b)
=>
[
{:c ({:v 40} {:v nil} {:v 11})}
{:c ({:v 60} {:v nil} {:v nil})}
{:c ({:v 70} {:v 66} {:v 22})}
]
Thanks

I guess you could do it nicer:
(defn to-lookup [table]
(into {}
(for [t table] (apply hash-map ((comp (partial map :v) :c) t)))))
(defn create [lookups k]
(let [values (for [lookup lookups] (get lookup k nil))
l (map (partial hash-map :v) values)]
{:c (cons (hash-map :v k) l)}))
(defn special-merge [& ts]
(let [lookups (map to-lookup ts)
allkeys (->> lookups (mapcat keys) distinct sort)]
(map (partial create lookups) allkeys)))
Output:
user=> (pprint (special-merge tab-a tab-b))
({:c ({:v 40} {:v nil} {:v 11})}
{:c ({:v 60} {:v nil} {:v nil})}
{:c ({:v 70} {:v 66} {:v 22})})
nil
user=>

Related

DrRacket – Finding total number of vowels in list of characters

I am using DrRacket on the Beginner Language mode.
Code below:
(define vowels '(#\a #\e #\i #\o #\u))
(define total 0)
(define (any-in-list lst check)
(cond
[(empty? lst) (+ 0 total)]
[(member? (first lst) check) (add1 total)]
[else (any-in-list (rest lst) check)]))
(define (count-vowels string)
(any-in-list (string->list string) vowels))
(count-vowels "how do i do this?")
The total value stays stuck at 1. After debugging, I realized that the 2nd cond statement evaluates to #true and then stops. How can I keep it going for the rest of the list after updating the total value?
You forgot to recurse when you found a match.
Also, since total is 0, (+ 0 total) is always 0, and (add1 total) is always 1.
Don't try to use global variables and mutation - recurse and use the recursive value.
(cond
; The empty list contains nothing, so the result is 0.
[(empty? lst) 0]
; If the first element is a member, the result is
; one more than the count in the tail.
[(member? (first lst) check) (add1 (any-in-list (rest lst) check))]
; Otherwise, the count is the same as in the tail.
[else (any-in-list (rest lst) check)]))
molbdnilo's answer explains the OP's issue and provides a correct solution;
since "Beginner Language" is mentioned, it may be worth
looking at how a solution might be constructed using the method
for which BSL (Beginning Student language) in DrRacket is apparently intended.
Following the HtDF (How to Design Functions) recipe, one can write the following
stub, incorporating signature and purpose, and "check-expect" examples:
(Note: layout differs slightly from HtDF conventions)
(define (count-vowels str) ;; String -> Natural ) *stub define* ;; *signature*
;; produce the count of vowel characters in str ) *purpose statement*
0 ) ) *stub body* (a valid result)
(check-expect (count-vowels "") 0 ) ) *examples*
(check-expect (count-vowels "a") 1 ) )
(check-expect (count-vowels "b") 0 ) )
(check-expect (count-vowels "ab") 1 ) )
(check-expect (count-vowels "ae") 2 ) )
The first check-expect already passes; now write inventory and template;
count-vowels will have to do something with each character in the string, but there is no
standard BSL function or template for this. However there is a template for doing something
with the elements of a list:
(define (fn lox) ;; (Listof X) -> Y ) *template*
(cond )
[(empty? lox) ... ] #|base case|# ;; Y )
[else (... #|something|# ;; X Y -> Y )
(first lox) (fn (rest lox))) ])) )
(define vowels (list #\a #\e #\i #\o #\u)) ) *inventory*
(member? x lox) ;; X (Listof X) -> Bool )
(string->list str) ;; String -> (Listof Char) )
So count-vowels can be a composition of string->list with a function derived from this
template, for which stub, signature, and check-expects are:
(define (count-vowels-in-list loc) ;; (Listof Char) -> Natural
0)
(check-expect (count-vowels-in-list empty) 0 )
(check-expect (count-vowels-in-list (cons #\a '())) 1 ) ;; (+ 1 0)
(check-expect (count-vowels-in-list (cons #\b '())) 0 ) ;; (+ 0 0)
(check-expect (count-vowels-in-list (list #\a #\b)) 1 )
(check-expect (count-vowels-in-list (list #\a #\e)) 2 )
Expanding the template and looking at the first check-expect, the |base case| can be filled in:
(define (count-vowels-in-list loc) ;; (Listof Char) -> Natural
(cond
[(empty? loc) 0 ]
[else (|something| (first loc) (count-vowels-in-list (rest loc))) ]))
For the next two check-expects, (rest loc) will be '(), so (|something| #\a 0) => 1 but
(|something| #\b 0) => 0
What distinguishes #\a from #\b is that (member? #\a vowels) => #true but
(member? #\b vowels) => #false so a descriptive name for |something| is add-1-if-vowel:
(define (add-1-if-vowel chr n) ;; Char Natural -> Natural
(if (member? chr vowels)
(add1 n)
n))
So a complete solution developed by following this systematic design method is:
(define vowels (list #\a #\e #\i #\o #\u))
(define (add-1-if-vowel chr n) ;; Char Natural -> Natural
(if (member? chr vowels)
(add1 n)
n))
(define (count-vowels-in-list loc) ;; (Listof Char) -> Natural
(cond
[(empty? loc) 0 ]
[else (add-1-if-vowel (first loc) (count-vowels-in-list (rest loc))) ]))
(define (count-vowels str) ;; String -> Natural
(count-vowels-in-list (string->list str)))
(check-expect (count-vowels "") 0 )
(check-expect (count-vowels "a") 1 )
(check-expect (count-vowels "b") 0 )
(check-expect (count-vowels "ab") 1 )
(check-expect (count-vowels "ae") 2 )
(check-expect (count-vowels "how do i do this?") 5 ) ;; ^ (this is how :) ^

Write a function that counts the number of elements in a rosetree

Write a function
that counts the number of elements in a rosetree.
I tried counts the number of elements in a rosetree.
data RoseTree a = RoseNode a [RoseTree a]
deriving Show
things :: RoseTree String
things =
RoseNode "thing" [
RoseNode "animal" [
RoseNode "cat" [], RoseNode "dog" []
],
RoseNode "metal" [
RoseNode "alloy" [
RoseNode "steel" [], RoseNode "bronze" []
],
RoseNode "element" [
RoseNode "gold" [], RoseNode "tin" [], RoseNode "iron" []
]
],
RoseNode "fruit" [
RoseNode "apple" [
RoseNode "Granny Smith" [], RoseNode "Pink Lady" []
],
RoseNode "banana" [],
RoseNode "orange" []
],
RoseNode "astronomical object" [
RoseNode "Planet" [
RoseNode "Earth" [], RoseNode "Mars" []
],
RoseNode "Star" [
RoseNode "The Sun" [], RoseNode "Sirius" []
],
RoseNode "Galaxy" [
RoseNode "Milky Way" []
]
]
]
It should be 27, however, it returns 4.
EDIT: Here is my attempt:
roseSize x = case x of
RoseNode a [] -> 0
RoseNode a (x:xs) -> 1 + roseSize (RoseNode a xs)
It should be 27, however, it returns 4.
roseSize x = case x of
RoseNode a [] -> 0
RoseNode a (x:xs) -> 1 + roseSize (RoseNode a xs)
So you're not counting the sub-trees recursively. Try instead (fixed: base case to 1),
roseSize (RoseNode _ []) = 1
roseSize (RoseNode a (t:ts)) = roseSize t + roseSize (RoseNode a ts)
The missing part is roseSize t.
Otherwise you're only making recursive calls for the first layer of the tree.
If you evaluate your function by hand this becomes apparent,
roseSize things
~> roseSize (RoseNode "thing" [ animals, metals, fruits, astronomical_objects ]
~> 1 + roseSize (RoseNode "thing" [ metals, fruits, astronomical_objects ])
~> 1 + 1 + roseSize (RoseNode "thing" [ fruits, astronomical_objects ])
~> 1 + 1 + 1 + roseSize (RoseNode "thing" [ astronomical_objects ])
~> 1 + 1 + 1 + 1 + roseSize (RoseNode "thing" [])
~> 1 + 1 + 1 + 1 + 0
whereas with roseSize t in the function body the evaluation becomes
roseSize things
~> roseSize (RoseNode "thing" [ animals, metals, fruits, astronomical_objects ]
~> roseSize animals
+ roseSize (RoseNode "thing" [ metals, fruits, astronomical_objects ])
~> roseSize (RoseNode "animal" [ cat, dog ])
+ roseSize (RoseNode "thing" [ metals, fruits, astronomical_objects ])
~> roseSize cat
+ roseSize (RoseNode "animal" [ dog ])
+ roseSize (RoseNode "thing" [ metals, fruits, astronomical_objects ])
~> 1 -- given the base case of 1 instead of 0
+ roseSize (RoseNode "animal" [ dog ])
+ roseSize (RoseNode "thing" [ metals, fruits, astronomical_objects ])
~> ...
As an exercise, making this function explicitly recursive is fine.
But you may want to consider a more general approach, either using higher-order functions like PF. Castro does it, or an existing data structure like Data.Tree of containers:
import qualified Data.Tree as T
import Data.Tree (Tree(..))
things :: Tree String
things = Node "thing" [ animals, metals, fruits, astronomical_objects ]
where
animals = Node "animal" (map pure [ "cat", "dog" ])
metals = Node "metal" [ alloys, elements ]
alloys = Node "alloy" (map pure [ "steel", "bronze" ])
elements = Node "element" (map pure [ "gold", "tin", "iron" ])
fruits = ...
astronomical_objects = ...
Since a Data.Tree is Foldable, you can use length on it.
So it's not necessary to define a custom roseSize function.
At this point you're counting the nodes in a tree, and not the leaves of a tree, with leaves being the actual objects rather than the categories to which they belong. So you may actually be interested in counting the leaves.
You could do that by creating a function that finds the leaves:
leaves :: Tree a -> [a]
leaves (Node x []) = ... -- x is a leaf
leaves (Node _x ts) = ... -- _x isn't a leaf
With this template you can't easily use explicit recursion, i.e. matching on Node x (t:ts) and calling leaves on ts, since then the non-leaf case eventually ends in the base case, making the exhausted category appear as a leaf. But you can use higher-order functions to abstract out the recursion, e.g. concat, map, or concatMap of Prelude.
Using a library rose tree gives you other advantages, too, for example a bunch of other type class instances (Applicative giving you pure "foo" to construct a singleton tree / leaf) and a pretty-printing function:
> putStrLn $ T.drawTree things
thing
|
+- animal
| |
| +- cat
| |
| `- dog
|
`- metal
|
+- alloy
| |
| +- steel
| |
| `- bronze
|
...
You should use map and fold with RoseTrees, e.g.:
size (RoseNode x xs) = 1 + (sum (map size xs))
where sum is just:
sum = foldl (+) 0

How to compare double quotes in Clojure?

(= "\"" "\"") ;; true
(let [ss "123\""]
(doseq [s ss]
(println s (= "\"" s) (.equals "\"" s))))
;; 1 false false
;; 2 false false
;; 3 false false
;; " false false
Why false in second case ?
Note the type of the elements given to you by doseq:
(let [ss "123\""]
(doseq [s ss]
(println (type s))))
You'll see that they're characters, yet you're comparing them against a string. That will always be false since the types don't match.
Compare against a character instead:
(let [ss "123\""]
(doseq [s ss]
(println s (= \" s))))
1 false
2 false
3 false
" true

Clojure macro for string template replacement

This is my first Clojure macro -- I am an uber-noob.
Yesterday I posted and refined a string template replacement function. Several people suggested that the keys could be replaced at compile-time. Here is my first attempt:
(defn replace-templates*
"Return a String with each occurrence of a substring of the form {key}
replaced with the corresponding value from a map parameter.
#param str the String in which to do the replacements
#param m a map of template->value
#thanks kotarak https://stackoverflow.com/questions/6112534/
follow-up-to-simple-string-template-replacement-in-scala-and-clojure"
[^String text m]
(let [builder (StringBuilder.)]
(loop [text text]
(cond
(zero? (count text))
(.toString builder)
(.startsWith text "{")
(let [brace (.indexOf text "}")]
(if (neg? brace)
(.toString (.append builder text))
(if-let [[_ replacement] (find m (subs text 1 brace))]
(do
(.append builder replacement)
(recur (subs text (inc brace))))
(do
(.append builder "{")
(recur (subs text 1))))))
:else
(let [brace (.indexOf text "{")]
(if (neg? brace)
(.toString (.append builder text))
(do
(.append builder (subs text 0 brace))
(recur (subs text brace)))))))))
(def foo* 42)
(def m {"foo" foo*})
(defmacro replace-templates
[text m]
(if (map? m)
`(str
~#(loop [text text acc []]
(cond
(zero? (count text))
acc
(.startsWith text "{")
(let [brace (.indexOf text "}")]
(if (neg? brace)
(conj acc text)
(if-let [[_ replacement] (find m (subs text 1 brace))]
(recur (subs text (inc brace)) (conj acc replacement))
(recur (subs text 1) (conj acc "{")))))
:else
(let [brace (.indexOf text "{")]
(if (neg? brace)
(conj acc text)
(recur (subs text brace) (conj acc (subs text 0 brace))))))))
`(replace-templates* ~text m)))
(macroexpand '(replace-templates "this is a {foo} test" {"foo" foo*}))
;=> (clojure.core/str "this is a " foo* " test")
(println (replace-templates "this is a {foo} test" {"foo" foo*}))
;=> this is a 42 test
(macroexpand '(replace-templates "this is a {foo} test" m))
;=> (user/replace-templates* "this is a {foo} test" user/m)
(println (replace-templates "this is a {foo} test" m))
;=> this is a 42 test
Is there a better way to write this macro? In particular, the expanded version of each value is not getting namespace-qualified.
I would try reduce the repeated stuff. I adjusted the function to use your macro approach of an accumulator and let replace-templates* do the rest via (apply str ...). In that way one can re-use the function in the macro.
(defn extract-snippets
[^String text m]
(loop [text text
snippets []]
(cond
(zero? (count text))
snippets
(.startsWith text "{")
(let [brace (.indexOf text "}")]
(if (neg? brace)
(conj snippets text)
(if-let [[_ replacement] (find m (subs text 1 brace))]
(recur (subs text (inc brace)) (conj snippets replacement))
(recur (subs text 1) (conj snippets \{)))))
:else
(let [brace (.indexOf text "{")]
(if (neg? brace)
(conj snippets text)
(recur (subs text brace) (conj snippets (subs text 0 brace))))))))
(defn replace-templates*
[text m]
(apply str (extract-snippets text m)))
(defmacro replace-templates
[text m]
(if (map? m)
`(apply str ~(extract-snippets text m))
`(replace-templates* ~text ~m)))
Note: in your macro, you didn't unquote the m. So it only works, because you had def'd it before. It wouldn't with (let [m {"a" "b"}] (replace-templates "..." m)).
Change (defn m {"foo" foo*}) to (def m {"foo" foo*}) and it seems to work.

Multithreaded bouncing balls program using agents in Clojure

I have written a multithreaded bouncing balls program in clojure. After starting the animation thread, I do-
(send-balls)
to start the bouncing balls threads. The balls dont move and this is displayed on the console -
(#<Agent#5675b3ee FAILED: #<Ref#313d21d6: {:x 759, :y 629, :x-speed 3, :y-speed 1}>> #<Agent#22cf3539 FAILED: #<Ref#247881db: {:x 794, :y 258, :x-speed 2, :y-speed 3}>> #<Agent#51af4309 FAILED: #<Ref#445ead9d: {:x 831, :y 251, :x-speed 4, :y-speed 2}>>)
Can someone point out whats happening here?
(import
'(java.awt Color Graphics Dimension)
'(java.awt.image BufferedImage)
'(javax.swing JPanel JFrame))
(def width 1000)
(def height 1000)
(def number-of-balls 3)
(def rad 20)
(def origin-x 100)
(def origin-y 100)
(def box-height 500)
(def box-width 700)
(def max-x (+ origin-x box-width (* 4 rad)))
(def max-y (+ origin-y box-height (* 4 rad)))
(def min-x origin-x)
(def min-y origin-y)
(defn init-x
[]
(+ (rand-int (- max-x min-x)) min-x))
(defn init-y
[]
(+ (rand-int (- max-y min-y)) min-y))
(defstruct ball :x :y :x-speed :y-speed)
(def balls
(apply vector (map (fn [_] (ref (struct ball (init-x) (init-y)
(rand-int 10) (rand-int 10))))
(range number-of-balls))))
(def ball-agents (apply vector (map agent balls)))
(defn get-ball
[n]
(balls n))
(defn set-new-x
[ball]
(let [x (#ball :x)
x-speed (#ball :x-speed)
new-x (+ x x-speed)]
(dosync
(if (and (>= new-x min-x) (<= new-x max-x))
(ref-set ball (assoc #ball :x new-x))
(ref-set ball (assoc #ball :x-speed (* -1 x-speed)))))
(println "the new x is " #(ball :x)))
#ball)
(defn set-new-y
[ball]
(let [y (#ball :y)
y-speed (#ball :y-speed)
new-y (+ y y-speed)]
(dosync
(if (and (>= new-y min-y) (<= new-y max-y))
(ref-set ball (assoc #ball :y new-y))
(ref-set ball (assoc #ball :y-speed (* -1 y-speed))))))
#ball)
(defn paint-balls
[bg x y]
(doto bg
(.setColor (. Color red))
(.fillOval x y rad rad)))
(defn render
[g]
(let [img (new BufferedImage width height
(. BufferedImage TYPE_INT_ARGB))
bg (. img (getGraphics))]
(doto bg
(.setColor (. Color white))
(.fillRect 0 0 (. img (getWidth)) (. img (getHeight)))
(.setColor (. Color red))
(.drawRect origin-x origin-y (+ origin-x box-width) (+ origin-y box-height)))
(dorun
(for [i (range number-of-balls)]
(do
(paint-balls bg (#(get-ball i) :x) (#(get-ball i) :y)))))
(. g (drawImage img 0 0 nil))
(. bg (dispose))))
(def panel (doto (proxy [JPanel] []
(paint [g] (render g)))
(.setPreferredSize (new Dimension
width
height))))
(def frame (doto (new JFrame) (.add panel) .pack .show))
(def animator (agent nil))
(defn bounce
[x]
(while true
(set-new-x #*agent*)
(set-new-y #*agent*)
(. Thread (sleep 100))
(println "here in bounce " *agent*)))
(defn animation
[x]
(send-off *agent* animation)
(. panel (repaint))
(. Thread (sleep 100)))
(defn send-balls
[]
(doall
(for [i (range number-of-balls)]
(do
(send-off (ball-agents i) bounce)))))
(send-off animator animation)
As i see the main problem - functions that you send-off to agents operate NOT with agent, but with its value (the ref). By eliminating # in set-new-x and set-new-y functions you could make it work.
(ns balls)
(import
'(java.awt Color Graphics Dimension)
'(java.awt.image BufferedImage)
'(javax.swing JPanel JFrame))
(def width 1000)
(def height 1000)
(def number-of-balls 3)
(def rad 20)
(def origin-x 100)
(def origin-y 100)
(def box-height 500)
(def box-width 700)
(def max-x (+ origin-x box-width (* 4 rad)))
(def max-y (+ origin-y box-height (* 4 rad)))
(def min-x origin-x)
(def min-y origin-y)
(defn init-x
[]
(+ (rand-int (- max-x min-x)) min-x))
(defn init-y
[]
(+ (rand-int (- max-y min-y)) min-y))
(defstruct ball :x :y :x-speed :y-speed)
(def balls
(apply vector (map (fn [_] (ref (struct ball (init-x) (init-y)
(rand-int 10) (rand-int 10))))
(range number-of-balls))))
(def ball-agents (apply vector (map agent balls)))
(defn get-ball
[n]
(balls n))
(defn set-new-x
[ball]
(let [x (ball :x)
x-speed (ball :x-speed)
new-x (+ x x-speed)]
(dosync
(if (and (>= new-x min-x) (<= new-x max-x))
(alter ball assoc :x new-x)
(alter ball assoc :x-speed (* -1 x-speed)))))
ball)
(defn set-new-y
[ball]
(let [y (ball :y)
y-speed (ball :y-speed)
new-y (+ y y-speed)]
(dosync
(if (and (>= new-y min-y) (<= new-y max-y))
(alter ball assoc :y new-y)
(alter ball assoc :y-speed (* -1 y-speed))))
ball))
(defn paint-balls
[bg x y]
(doto bg
(.setColor (. Color red))
(.fillOval x y rad rad)))
(defn render
[g]
(let [img (new BufferedImage width height
(. BufferedImage TYPE_INT_ARGB))
bg (. img (getGraphics))]
(doto bg
(.setColor (. Color white))
(.fillRect 0 0 (. img (getWidth)) (. img (getHeight)))
(.setColor (. Color red))
(.drawRect origin-x origin-y (+ origin-x box-width) (+ origin-y box-height)))
(dorun
(for [i (range number-of-balls)]
(do
(paint-balls bg (#(get-ball i) :x) (#(get-ball i) :y)))))
(. g (drawImage img 0 0 nil))
(. bg (dispose))))
(def panel (doto (proxy [JPanel] []
(paint [g] (render g)))
(.setPreferredSize (new Dimension
width
height))))
(def frame (doto (new JFrame) (.add panel) .pack .show))
(def animator (agent nil))
(defn bounce
[ball_cur]
(do
(Thread/sleep 100)
(send-off *agent* bounce)
(set-new-x (set-new-y ball_cur))))
(defn animation
[x]
(send-off *agent* animation)
(. panel (repaint))
(. Thread (sleep 100)))
(defn send-balls
[]
(doall
(for [i (range number-of-balls)]
(do
(send-off (ball-agents i) bounce)))))
(send-off animator animation)
(send-balls)
I think you don't need refs inside agents. Please see below for a working version with just agents. You can load the code eg. via load-file then simply issue start. A frame will pop up with the desired animation. It can be stopped by reset!ing the returned atom to false. You can have as you many independent animation frames as you wish by calling start more than once.
Hope that helps.
(import
'(java.awt Color Graphics Dimension)
'(java.awt.image BufferedImage)
'(javax.swing JPanel JFrame))
(def width 1000)
(def height 1000)
(def number-of-balls 3)
(def rad 20)
(def origin-x 100)
(def origin-y 100)
(def box-height 500)
(def box-width 700)
(def min-borders {:x origin-x
:y origin-y})
(def max-borders {:x (+ origin-x box-width (* 4 rad))
:y (+ origin-y box-height (* 4 rad))})
(defn init
[coord]
(+ (rand-int (- (get max-borders coord) (get min-borders coord)))
(get min-borders coord)))
(defn init-balls
[]
(->> (repeatedly number-of-balls
#(array-map :x (init :x) :y (init :y)
:x-speed (rand-int 10)
:y-speed (rand-int 10)))
(map agent)
vec))
(defn update-coordinate
[ball coord-key speed-key]
(let [coord (get ball coord-key)
speed (get ball speed-key)
new-c (+ coord speed)]
(if (<= (get min-borders coord-key) new-c (get max-borders coord-key))
(assoc ball coord-key new-c)
(assoc ball speed-key (- speed)))))
(defn paint-ball
[bg x y]
(doto bg
(.setColor Color/red)
(.fillOval x y rad rad)))
(defn render
[g balls]
(let [img (BufferedImage. width height BufferedImage/TYPE_INT_ARGB)
bg (.getGraphics img)]
(doto bg
(.setColor Color/white)
(.fillRect 0 0 (.getWidth img) (.getHeight img))
(.setColor Color/red)
(.drawRect origin-x origin-y
(+ origin-x box-width) (+ origin-y box-height)))
(doseq [b balls]
(let [ball #b]
(paint-ball bg (:x ball) (:y ball))))
(.drawImage g img 0 0 nil)))
(defn bounce
[ball running?]
(when #running?
(send-off *agent* bounce running?))
(Thread/sleep 100)
(-> ball
(update-coordinate :x :x-speed)
(update-coordinate :y :y-speed)))
(defn animation
[panel running?]
(while #running?
(javax.swing.SwingUtilities/invokeAndWait #(.repaint panel))
(Thread/sleep 100)))
(defn start
[]
(let [running? (atom true)
balls (init-balls)
panel (doto (proxy [JPanel] []
(paint [g] (render g balls)))
(.setPreferredSize (Dimension. width height)))
frame (doto (JFrame.) (.add panel) .pack .show)]
(doseq [b balls]
(send-off b bounce running?))
(future (animation panel running?))
running?))
Your send (or send-off) function (in this case: bounce) should return the (new) state of the agents. This is fully described here.
There are a couple of problems with the code -
As Maurits pointed out, bounce does not return the new state of the agent.
There is no place in the bounce function where bounce is added to the action queue of the agent again. This is needed as the new coordinated need to be calculated again and again.

Resources