[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

Re: please help making my Lisp more idiomatic

William James

11/11/2015 10:56:00 PM

Ken Tilton wrote:

> > Thank you for your help. Since I don't have a good mental model of
> > all the intricacies of loop at the moment, I decided to use dotimes.
>
> That's fine, but loop is worth an hour of study:
>
> > (let ((x (random (reduce #'+ probs)))
> > (n 0))
> > (dolist (p probs)
> > (if (< x p)
>
> If there is no else then I use when else I use if.
> When there is no else I use when.
>
> > (return n))
> > (incf n)
> > (decf x p))))
>
> (loop for x = (random (reduce #'+ probs)) then (- x p)
> for n upfrom 0
> for p in probs
> when (< x p) return n)
>
> At least i think that is the same.

MatzLisp (Ruby):

probs = [2,4,8]
$boundaries = (0 ... probs.size).
map{|i| [probs.take(i).reduce(0, :+), i]}.reverse
$rand_limit = probs.reduce :+

def rand_pick
x = rand( $rand_limit )
$boundaries.find{|b,i| x>= b}[1]
end

## Testing.
counts = [0] * probs.size
999888.times{ counts[rand_pick] += 1 }
counts.map{|n| (n.to_f / counts[0]).round(2)}

===>[1.0, 2.0, 3.99]

--
They [the Puritans] bored holes through Quakers' tongues with red-hot irons at
Boston, drowned the Baptists at Salem, stripped women and tied them to cart
tails, and whipped them from Boston to Dedham.
--- The Old Guard, March 1863, p. 59