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 ()?
"()" 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With