state between cycles

I want to make a random cycle of notes, but the first note has to be the same as the last note of the previous cycle. how?

like this?

d1 $ s "superpiano"
   + n (scale "major" 
        $ fast 4
        $ whenmod 4 3 (1 ~> )     --- <<< THIS
        $ segment 1 $ irand 8 )

every fourth cycle, shift time by one (play a note from the future. it will then be repeated when the future becomes the present)