Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

() in Function Variable and Application

Tags:

haskell

The Types and Functions lecture presents the function:

f44 :: () -> Integer
f44 () = 44

I typed the following:

ghci> let f () = 5
ghci> f ()
5

But, I'm confused by the () in let f (). Typically, as a beginner, I've seen an immutable variable following the function name, i.e. f.

What is the name of () when it's listed after let f ...? How about when it's used in the function application, f ()?

like image 730
Kevin Meredith Avatar asked Aug 29 '26 02:08

Kevin Meredith


2 Answers

"()" is usually pronounced "unit".

In Haskell, it is both the name of a type, as seen in

f44 :: () -> Integer

and the name of the only value that exists of that type, as seen in

f44 () = 44

where it is used for pattern matching.

This more familiar-looking definition would provide an equivalent but more verbose type:

data Unit = Unit
f45 :: Unit -> Integer
f45 Unit = 45

Nothing stops you from binding () to a name, just like you can for any other value:

Prelude> let f () = 5
Prelude> :t f
f :: Num a => () -> a
Prelude> let name = ()
Prelude> :t name
name :: ()
Prelude> name
()
Prelude> f name
5
like image 187
molbdnilo Avatar answered Aug 30 '26 15:08

molbdnilo


There is nothing special about this function:

f44 :: () -> Integer
f44 () = 44

The key thing to understand here is that () is the type with only a single inhabitant value (). So the type () can have only a value of (). In fact it's defined like this:

data () = ()

When you do this in ghci:

λ> let f () = 5

You are creating a function of type Num a => () -> a. You can inspect that yourself in ghci:

λ> :t f
f :: Num a => () -> a

What is the name of () when it's listed after let f ...?

You are using pattern matching to implement a function f which given a value of () gives you 5.

How about when it's used in the function application, f ()?

It's the usual function application. You are applying a value of () to the function f and that will produce 5 according to your function definition.

like image 31
Sibi Avatar answered Aug 30 '26 17:08

Sibi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!