Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does racket allow for function overloading?

Tags:

racket

I am new to Lisp-scheme and fairly new to the functional paradigm as a whole, and am currently doing an assignment which requires me to overload a function with the same name, but different sets of parameters in racket. Below is an example of what I'm trying to achieve:

#lang racket

(define (put-ball-in-box two-by-fours nails ball)
  ... )

(define (put-ball-in-box box ball)
  ... )

These are not the actual functions, but close enough. As implied, both functions would put a ball in a box, but one would assemble the box from its components first, then call the other. Obviously, when I try the above in DrRacket or using the command line, I get a module: duplicate definition for identifier ... error.

Is there a way to achieve this in racket?

Maybe the answer is right in front of me, but I have spent the last two hours searching for this and couldn't find anything, so would appreciate any pointers.

Thank you.

like image 550
Claudius Avatar asked Mar 06 '23 23:03

Claudius


1 Answers

It doesn't in the usual sense of "writing another definition somewhere else."

It allows shadowing, which is defining a procedure with the same name as an imported procedure. Thus you can (define + ...) and your definition of + will hide the + from racket/base. If you want the original procedure, then you can do something like the following, where I define + to be either addition or string-appending.

 #lang racket/base
 (require (rename-in racket/base (+ base:+)))

 (define (+ . args)
   (if (andmap string? args)
       (apply string-append args)
       (apply base:+ args)))

Another thing you can do is use racket/match to have different behavior based on the shape of the argument.

#lang racket/base
(require racket/match)
(define (fib . arg)
  (match arg
   [(list n) (fib n 1 0)]
   [(list 1 a b) a]
   [(list 0 a b) b]
   [(list n a b) (fib (sub1 n) (+ a b) a)]))

This second example still doesn't quite do what you want since you have to go to the original definition point and modify the match clauses. But it might be sufficient for your purposes.

A more complicated example would be to use custom syntax to create a define/overload form. But I think you'll find the racket/match solution to be best.

like image 179
law-of-fives Avatar answered Apr 30 '23 08:04

law-of-fives