[racket] Signature for an optional-argument function?

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Fri Aug 23 09:28:33 EDT 2013

On Aug 23, 2013, at 12:28 AM, Alexander D. Knauth wrote:

> Right now I'm using Intermediate Student Language, not Racket
> I was wondering if I could define a function with optional arguments

In ISL+ you cannot defined variable-arity functions. In Racket there are many mechanism for doing so (all reduced to one in the core language). You can simulate the idea in ISL+, which you might have done. 

> So how do I write the signature?  

In ISL+, that depends on how you simulate it. The best way is to define a function that consumes a list of values but expects specific kinds of values. For your flexible fold below, you could write: 

;; [List (X Y -> Y) (Z -> X) Y [List-of Z]] 
;; or
;; [List (X Y -> Y) Y [List-of Z]] 
;; ->  Y

If you do not like 'or', introduce a separate data definition like this: 

;; [FoldArgument X Y Z] is one of: 
;; -- [List (X Y -> Y) (Z -> X) Y [List-of Z]] 
;; -- [List (X Y -> Y) Y [List-of Z]] 

and then you write 

;; [FoldArgument X Y Z] -> Y 

In Racket, we tend to use square brackets in documentation. In contracts -- a checked form of signature for module boundaries -- we have a notation for this idea. 

> The particular example I'm thinking of is an abstract fold function that has an optional argument (a function) for the contribution of the first:  
> (check-expect (fold + 0 (list 1 2 3)) 6)           ;sum, without optional argument
> (check-expect (fold + identity 0 (list 1 2 3)) 6)  ;sum, with identity as the optional argument
> (check-expect (fold + string-length 0 (list "a" "bc" "def")) 6)  ;total-string-length

I would run your example as 

  (fold (compose + string-length) 0 '("a" ...)) 

and be done. 

> You could also design a weird function that does completely different things depending on what the arguments are, like this:

For fun, you can write any kind of function you like. 

As long as you design these functions to match the structure of the data definition, your fellow programmers won't mind. Otherwise, they will not like you. See my home page re 'psychopath'. 

-- Matthias

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20130823/4eaa8ef6/attachment-0001.html>

Posted on the users mailing list.