HASKELL / CHAPTER 01
Expressions, types, and application
IntermediateRead Haskell functions as typed expressions rather than mutable procedures.
By the end of this chapter
- Read a curried function type
- Apply functions with spaces
- Distinguish integer and fractional division
The idea
Enter with basic programming and algebraic expressions understood. Haskell definitions name values rather than mutable storage locations. A function maps its inputs to a result, and a type signature documents that relationship. Integer -> Integer -> Integer describes a function taking an Integer and returning another function that takes an Integer. Ordinary two-argument application follows naturally from that structure.
Function application uses spaces and binds more tightly than infix arithmetic. Parentheses group an expression when it should become one argument. Use div for integer division when working with Integer, while / requires a fractional numeric type. This course uses nonnegative division examples unless it explicitly discusses signed behavior. Read the type and grouping before evaluating a line; familiar symbols can behave differently from those in imperative languages.
add :: Integer -> Integer -> Integer
add x y = x + y
main :: IO ()
main = print (add 3 (4 * 2))11
The parenthesized multiplication produces the second argument eight. add receives three and eight and returns eleven.
Try it yourself
Define triple :: Integer -> Integer and use it on a parenthesized sum.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING