简体   繁体   中英

Haskell: functions and values

I am a beginner in Haskell and have a problem with the def of functions in Haskell. Values are functions in Haskell, right? (+3) 3 = 6 but what does (+3) (+3) mean. Does (+3) counts as an value ?

(+3) isn't what you probably think it is. In other languages, this means the numerical value positive‑three . In Haskell it's the partial application of the + operator, and is a function taking one argument (the other number to add). It adds three to whatever it's given. So (+3) x is the application of the function (+3) to the value x and returns x+3 . However, (+3) (+3) tries to add 3 to the function (+3) which doesn't make sense and gives a type error.

It might help to imagine replacing + with a regular function called plus :

plus x y = y + x

Then, (+3) is equivalent to plus 3 , and (+3) 3 to (plus 3) 3 which is the same as plus 3 3 . However, (+3) (+3) is equivalent to (plus 3) (plus 3) or plus 3 (plus 3) which doesn't make sense.

You might want to think about what (+3) . (+3) (+3) . (+3) means. This chains together two applications of adding three, and is a single-argument function that adds six.

(+3) (+3) is simply a type error and, therefore, it won't compile.

The type of (+3) is Int -> Int , which means that when applying an Int , we get another Int . It also means that you can only apply values of type Int !

So, you can't apply to (+3) a value of type Int -> Int , only values of type Int .

So yes, (+3) is value, but not of the right type to apply it to a function that expects a value of type Int .

Int can't be unified with Int -> Int because they have different type constructor , which makes them different types, as pointed out by @DanielWagner. The outermost constructor of Int -> Int is -> while the outermost constructor of Int is simply Int . It is sufficient that two types have different outermost constructor for considering them different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM