21

Is it possible to set a default value to some of arguments in Racket?

Like so in Python:

def f(arg=0)
    ...
Vladimir Keleshev
  • 13,753
  • 17
  • 64
  • 93

1 Answers1

31

Yes; take a look at: declaring optional arguments.

For example:

(define (f [arg 0])
  (* arg 2))

Racket also supports functions with keyword arguments. The link should lead to documentation that talks about them too. Good luck!

dyoo
  • 11,795
  • 1
  • 34
  • 44
  • 1
    Btw, do you think it's a good idea to use optional arguments for passing state in recursive functions? – Vladimir Keleshev Aug 20 '11 at 17:47
  • 1
    Sometimes, but it often backfires on me. If the optional argument is some accumulator, for example, then if I forget to pass the accumulator in my recursive call somewhere, well, oops. :) – dyoo Aug 20 '11 at 17:50
  • 2
    wrt the use of optional arguments for storing state in recursive functions, I see that as a slight evil in that you're abstraction is leaky. I prefer the pattern with an inner-define like so: (define (foo a b c) (define (foo a b c state) #|...|#) (foo a b c 'init-state)) – Marty Neal Aug 23 '11 at 20:51
  • That what I was thinking about. But, damn, (define (foo a b c [state '()])) is so much easier to type :) – Vladimir Keleshev Aug 23 '11 at 23:07
  • 3
    Use a name-let. (define (tree-sum t) (let loop ([t t]) (if (tree-node? t) (apply + (map loop (tree-children t)))) (tree-val t)))) Then you can add whichever state arguments you need to the loop function without leaking them into the interface of the tree-sum function. @Halst – Guillaume Marceau Feb 20 '12 at 23:21
  • How to make the argument optional *and* a keyword argument, like it actually is in the OP? – Zelphir Kaltstahl Jan 29 '17 at 00:15