The following tips are for Racket:
Default arguments
Especially useful for creating aliases for long function names that are used often.
Assume the golf allows you to write a function that consumes the argument, and assume you need to use reverse
a lot.
You'll start with something like:
(λ(x) ... reverse ... reverse ... reverse ...
You can instead take in an additional argument, with a shorter name than reverse
, and set its default value to reverse
:
(λ(x[r reverse]) ... r ... r ... r ...
Furthermore, it's useful if you have a helper function that you use in many places with some of the same arguments. Remember to reorder the arguments to the function as needed, so you can use as many default arguments as possible, and remove the arguments from multiple callsites.
match
This one is a little harder to summarize in a small post, so read up on the Racket Docs for this one.
In a nutshell, match
allows you extract elements and sequences of elements in a certain order from a list, and the quasiquote syntax lets you stitch the mutilated list back together:
(match (range 10)
[`(,xs ... 3 ,ys ... 6 ,zs ...)
`(,@(map f xs) 3 ,@(map f ys) 6 ,@(map f sz))]
...
It also gives you an easy way to work with regular expressions and do additional computation on the resulting groups afterwards,
Named let
See the named let proc-id ...
syntax here.
This allows you to write recursive functions that are called immediately without define
or actually calling the function after you've defined it.
Something like:
(define (fib i)
(if (< i 2) i
(+ (fib (- i 1)) (fib (- i 2)))))
(fib 10)
can be shortened to:
(let fib {[i 10]}
(if (< i 2) i
(+ (fib (- i 1)) (fib (- i 2)))))
This last one is silly, but I haven't been able to use this little trick anywhere so far:
(apply map list matrix)
takes a transpose of matrix
, where matrix
is some rectangular list of lists, like '((1 2 3) (a b c))
.
Let me know if this does prove to be useful.
I wouldn't call that binding. You are using different functions. In some cases, using an anonymous function is shorter than binding a variable. – Michael Vehrs – 2017-03-17T06:52:42.850
I'm not sure what your opinion has to do with the typical terminology used in scheme circles. I can assure you both ways are binding variables to a lexical scope, and
– Winny – 2017-03-18T23:08:25.290let
is often implemented in terms oflambda
.