On Thursday, April 11, 2019 at 1:50:23 PM UTC+8, travis....@gmail.com wrote:
>
> Hi All,
>
> I'm trying to better understand recursion. I decided to rewrite the 
> logmodr function from this blog post 
> <http://www.seascapemodels.org/rstats/2017/02/26/speeding-up-sims.html> as 
> a recursive function. I was easily able to write the recursive functions if 
> all but one of the arguments were set to default values. But I was 
> completely stumped by how to handle the situation without using default 
> argument values. After a considerable amount of flailing about, I finally 
> realized that I could accomplish this task by passing the arguments as a 
> struct (see code below). I find the struct approach relatively intuitive 
> but it strikes me as quite verbose. Are there other (better?) ways to 
> handle this task?
>

The trick is to use nested functions, like so:

(define (project-pop-1 y r k thetasd t)

  (define (logmod y)
    (define theta (flvector-ref (flnormal-sample 0.0 thetasd 1) 0))
    (* y (- r (* r (/ y k))) (exp theta)))
    
  (define (loop y i)
    (if (= i t)
        (list y)
        (cons y (loop (logmod y) (add1 i)))))

  (loop y 1))

(project-pop-1 1.0 1.8 20.0 0.1 25)

Also, multiplication accepts any number of arguments, instead of (* a (* b 
c)) when you can write (* a b c)

Also, if you want to use structures, you can use `struct-copy` and 
`match-define` and the code looks much nicer.  Your implementation of 
logmod can be written as:

(define (logmod-1 args-struct)
  (match-define (args y r k thetasd) args-struct)
  (define theta (flvector-ref (flnormal-sample 0.0 thetasd 1) 0))
  (define new-y (* y (- r (* r (/ y k))) (exp theta)))
  (struct-copy args args-struct [y new-y]))
Alex.


 

>
> Thanks,
>
> Travis
>
>
> #lang racket
>
> (require math)
>
> (struct args (y r k thetasd) #:transparent) ; only 'y' changes in 
> project-pop function below
>
> (define (logmod args-struct)
>   (define theta (flvector-ref (flnormal-sample 0.0 (args-thetasd 
> args-struct) 1) 0))
>   (args (* (args-y args-struct) (* (- (args-r args-struct) (* (args-r 
> args-struct) (/ (args-y args-struct) (args-k args-struct)))) (exp theta)))
>         (args-r args-struct)
>         (args-k args-struct)
>         (args-thetasd args-struct)))
>
> (define (project-pop args-struct t [i 1])
>   (define y (args-y args-struct))
>   (if (= i t)
>       (list y)
>       (cons y (project-pop (logmod args-struct) t (+ i 1)))))
>       
> (project-pop (args 1.0 1.8 20.0 0.1) 25)
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to