Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a function with no return value?

Can we create a function with void (i.e with no return value) in functional languages? Like Haskell or Scheme

like image 547
Jeff Yan Avatar asked Sep 10 '25 10:09

Jeff Yan


1 Answers

In Haskell, you can write a whole family of functions that return () (unit), which is equivalent to void in C languages:

foo :: a -> ()
foo _ = ()

bar :: a -> b -> ()
bar _ _ = ()

You'll notice, however, that my implementations ignore their input, and simply return (), so they don't do anything.

You can call them like this:

Prelude> foo 42
()
Prelude> bar 42 "foo"
()

but this still doesn't accomplish anything.

You can, on the other hand, write functions that return IO (), like this:

main :: IO ()
main = putStrLn "Hello, world!"

but this is now impure. While this produces a side-effect, you could argue whether or not it's functional. At the very least, in Haskell, you can't call impure code from pure code (this is by design), so it doesn't compose.

like image 90
Mark Seemann Avatar answered Sep 12 '25 23:09

Mark Seemann