Settings

Theme

Solving LeetCode problems with Racket: I don't know what I expected

herecomesthemoon.net

3 points by TwentyPosts a year ago · 1 comment

Reader

gus_massa a year ago

> You might think “So what’s the big deal? It’s not statically typed, just runtime-enforced contracts.” and you’re completely right. That said, the trick is going to come in handy soon.

If you use typed/racket, they compiler checks a lot of them at compilation time, and even use them to eliminate implicit types checks.

  > (let ([huge-list (range 1e7)])
  >   (begin 
  >     (displayln (current-process-milliseconds))
  >     (first (map add1 huge-list))
  >     (displayln (current-process-milliseconds))
  >   )
  > )

There is some magic when you use in-range inside map like:

  >  (first (map add1 (in-range 1e7)))
It would be nice if the compiler can automatically fix this examplet, but it has to be an incredible smart compiler.

> Let’s take a look at how the Racket standard library implements this macro (this is what proper Racket formatting looks like, apparently).

A lot of Racket is written in a simplified version of Racket informally call #'kernel. The problem is that #'kernel is very difficult to use because it has only the minimal stuff. One of the first definitions is `and`, so that explains the ugly definition. After a few modules that add more and more friendly tools, it's possible to define `and` as

  (define-syntax (my-and stx)
    (syntax-case stx ()
      [(_) #'#t]
      [(_ x) #'x]
      [(_ x y ...) #'(if x (my-and y ...) #f)]))

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection