Is this possible to define a function with no arguments in racket?
Asked Answered
S

3

6

I'm trying to define a function in Racket which takes no arguments. All the examples that I have seen take one or more arguments. How can I do that?

Scud answered 19/11, 2013 at 20:59 Comment(0)
P
9
(define (fun1)
  "hello")

(define fun2
  (lambda ()
    "world"))

(define fun3
  (thunk
   "I am back"))      

(fun1)
=> "hello"
(fun2)
=> "world"
(fun3)
=> "I am back"

EDIT

If, as @Joshua suggests, you want a procedure which can take any argument(s) and ignore them, the equivalent definitions would be:

(define (fun1 . x)
  "hello")

(define fun2
  (lambda x
    "world"))

(define fun3
  (thunk*
   "I am back"))      

(fun1)
(fun1 1 2 3)
=> "hello"

(fun 2)
(fun2 4 5 6 7)
=> "world"

(fun3)
(fun3 8 9)
=> "I am back"
Politics answered 19/11, 2013 at 21:3 Comment(5)
Great, Thanks. What is thunk?Scud
@Scud The same thing as lambda (), see docs.racket-lang.org/reference/…Politics
You might also include (lambda args "hello world") since it can be called with zero arguments (but point out that it can be called with more, too).Groos
Than How can be the definition of a contract for the fun1 (in the first box)? if it takes no arguments and returns a hash table? This does not work: (provide (contract-out [foo (-> hash? )]))Scud
@Scud If this answers your question, please consider accepting my answer.Politics
W
2

The answer can be found in HtDP 2e here:

http://www.ccs.neu.edu/home/matthias/HtDP2e/part_one.html#%28part._sec~3afuncs%29

"...Here are some silly examples:

(define (f x) 1)

(define (g x y) (+ 1 1))

(define (h x y z) (+ (* 2 2) 3))"

...then later...

"The examples are silly because the expressions inside the functions do not involve the variables. Since variables are about inputs, not mentioning them in the expressions means that the function’s output is independent of their input. We don’t need to write functions or programs if the output is always the same." (emphasis mine)

That is the answer to your question: you do not need to define no-argument functions, just define them as constants.

So instead of:

(define (fun) "hello")

You just need:

(define not-a-fun "hello")
Weaponry answered 1/1, 2015 at 4:4 Comment(1)
I disagree with this argument. For example, what if you wanted to define a function like this? (define (random-color) (color (random 256) (random 256) (random 256)))Payton
M
0

You can simply say

(define (hello-world)
  (displayln "Hello world"))

(hello-world)
Mansuetude answered 19/11, 2013 at 21:10 Comment(1)
That doesn't sound right: define: expected at least one variable after the function name, but found nonePayton

© 2022 - 2024 — McMap. All rights reserved.