() in Function Variable and Application

老子叫甜甜 提交于 2019-12-31 03:19:10

问题


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 ()?


回答1:


"()" 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



回答2:


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.




回答3:


() is called Unit or empty tuple. It holds no value.

In function definition, parentheses on the left side of the = are usually only used to pattern match your function parameters.

In your example, the () is practically useless. Your function would work without it and would be a zero parameter function then.

f44 :: Integer
f44 = 44


来源:https://stackoverflow.com/questions/29970012/in-function-variable-and-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!