Optional argument that can be completely omitted?
See @AlbertRetey's answer for all but trivial cases.
Don't use Optional
, nor If
. Use two definitions.
similarWords[string_] := Nearest[WordList[], string]
similarWords[string_, n_] := Nearest[WordList[], string, n]
I prefer this over just using arg___
and passing all arguments into Nearest
because it keeps the responsibility for argument checking with similarWords
. But of course just passing down everything is easier and quicker to write, and it's what I'd do in an interactive session (as opposed to a package or a situation where reusability and reliability is more important).
for your simple example Szabolcs suggestions is certainly the best you can do. If for some reason in a less simple situation you want the behavior you described with just one definition this is what you could do:
similarWords[string_, n_: Automatic] := If[n === Automatic,
Nearest[WordList[], string],
Nearest[WordList[], string, n]
]
note that Automatic
is just a symbol whose name is guaranteed to have no definition and seems to fit the intented behavior, it has no special functionality builtin. Technically you could just as well use any other "tag", including -1 as you suggested...
EDIT there has been some discussion if and when this or the two definition approach are to be prefered, and I think it is pretty clear that the two definition approach is best when it doesn't lead to code duplication. If it does, you might be better off with the single definition approach in this answer. Alternatively you could extract one or more functions which do what is common to both definitions and only call those and have the code which is different in the bodies of the two definitions...
I'd love to have a short syntax form for that. I'd use it more often:
similarWords[string_, n:(_|PatternSequence[]) ]:= Nearest[WordList[],string,n]