scheme - Difference between 3 methods of detecting true in Racket -


it seem big deal there significant differences in following 3 methods of counting number of true items?

#lang racket  (define (counttrue . vars)   (length (remove* (list #f) vars))    )  (define (counttrue2 . vars)   (define c 0)   (for ((item vars))     (when item (set! c (add1 c))))   c    )  (define (counttrue3 . vars)   (count (lambda(x) x) vars)    ) 

they produce identical results there reason why particular 1 should or should not chosen?

edit: on using time function, following results obtained 3 functions above , 2 each answers @chrisjester-young , @sylwester :

"---------- counttrue ------------" cpu time: 751 real time: 751 gc time: 16 "---------- counttrue2 ------------" cpu time: 946 real time: 947 gc time: 10 "---------- counttrue3 ------------" cpu time: 456 real time: 457 gc time: 8 "---------- counttrue_chris1 ------------" cpu time: 726 real time: 727 gc time: 9 "---------- counttrue_chris2 ------------" cpu time: 595 real time: 595 gc time: 8 "---------- counttrue_sylwester1 ------------" cpu time: 543 real time: 544 gc time: 7 "---------- counttrue_sylwester2 ------------" cpu time: 515 real time: 515 gc time: 7 

hence, "count lambda" method fastest.

the count version idiomatic (except i'd write (count identity items)). furthermore, set! version not idiomatic racket, , racket doesn't optimise use, can see timing tests.

here couple of alternatives timing pleasure:

  1. using for comprehensions:

    (for/sum ((x (in-list items)) #:when x) 1) 
  2. manual looping:

    (let loop ((sum 0)            (items items))   (cond ((null? items) sum)         ((car items) (loop (add1 sum) (cdr items)))         (else (loop sum (cdr items))))) 

Comments

Popular posts from this blog

PHP while loop dynamic rowspan -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

Spring Boot + JPA + Hibernate: Unable to locate persister -