Haskell Bindings
A binding gives a name to a value in a Haskell program. Other code can then use the name in place of the value.
A name can stand for a number
The binding links score to 42. Printing the name prints its value.
score = 42
main :: IO ()
main = print scoreA name can stand for text
The binding links name to a line of text. Printing the name prints that text.
name = "Ana"
main :: IO ()
main = putStrLn nameNames can feed a calculation
Two bindings hold the two counts. The calculation inside print adds their values.
apples = 4
bananas = 6
main :: IO ()
main = print (apples + bananas)Example
weekdayHours = 5
weekendHours = 3
totalHours = weekdayHours + weekendHours
main :: IO ()
main = print totalHoursKey points
- Binding: a line that links a name to a value with an equals sign.
- Name: the word on the left of the equals sign, such as score.
- Value: the data on the right of the equals sign, such as 42.
- Reuse: a bound name can be used many times after its binding.
- Order: a binding sits at the top level of the file, above main.
In this example, two bindings hold the hours for weekdays and the weekend. A third binding adds them, and main prints the total of 8.
Note
a binding cannot be reassigned later in the same program, unlike a variable in many other languages.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What happens if a program tries to give the name score a second, different value later in the same file?