[Racket/Scheme] Project Euler Problem 5 Solution


Ok ok, I have to admit that Racket is pretty cool sometimes😀 (despite it’s very verbous :D)
This is my solution for the problem 5:

#lang racket

(define (div-1-20? x)
  (let aux ([x x]
            [acc 1])
            (cond
              [(= 0 x) #f]
              [(= 21 acc) #t]
              [(= 0 (modulo x acc)) (aux x (add1 acc))]
              [else #f])))

;; Pretty cool
(for ([i (stop-after (in-naturals 1) div-1-20?)]
      #:when (div-1-20? i)) (display i))

The dark magic is provided by in-naturals, stop-after and the #:when clausole:

  • in-naturals provide a lazy sequence from start to +inf
  • stop-after make sure that for will stop when the predicate div-1-20? will be satisfied
  • when assures that only when div-1-20? will be satisfied the for body will be executed

As result this code runs in constant space and is no memory-consuming at all🙂

Bye!

Alfredo

2 thoughts on “[Racket/Scheme] Project Euler Problem 5 Solution

    • Coming from an Ocaml background, letrec is not far from my universe at all🙂
      I will fix the code this evening😛
      Thanks Riko,
      Bye!
      Alfredo

Lascia un commento

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...