13 August 2015

First, let’s start GHC’s interactive mode and call some functions, so we can get a very basic feel for Haskell. Open a terminal and type ghci. You will be greeted with something like this:

GHCi, version 6.12.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.

NOTE GHCi’s default prompt is Prelude>, but we’ll be using ghci> as our prompt for the ex- amples in this book. To make your prompt match the book’s, enter :set prompt "ghci> " into GHCi. If you don’t want to do this every time you run GHCi, create a file called .ghci in your home folder and set its contents to :set prompt "ghci> ".

Congratulations, you’re in GHCi! Now let’s try some simple arithmetic:

ghci> 2 + 15
17
ghci> 49 * 100
4900
ghci> 1892 - 1472
420
ghci> 5 / 2
2.5

ghci> (50 100) - 4999 1 ghci> 50 100 - 4999 1 ghci> 50 * (100 - 4999) -244950

ghci> True && False False ghci> True && True True ghci> False || True True ghci> not False True ghci> not (True && True) False

ghci> 5 == 5 True ghci> 1 == 0 False ghci> 5 /= 5 False ghci> 5 /= 4 True ghci> "hello" == "hello" True

Calling Functions

You may not have realized it, but we’ve actually been using functions this whole time. For in- stance, * is a function that takes two numbers and multiplies them. As you’ve seen, we apply (or call) it by sandwiching it between the two numbers we want to multiply. This is called an infix function.

Most functions, however, are prefix func- tions. When calling prefix functions in Haskell, the function name comes first, then a space, then its parameters (also separated by spaces). As an example, we’ll try call- ing one of the most boring functions in Haskell, succ:

ghci> succ 8
9

The succ function takes one parameter that can be anything that has a well-defined successor, and returns that value. The successor of an integer value is just the next higher number.

Now let’s call two prefix functions that take multiple parameters, min and max:

ghci> min 9 10
9
ghci> min 3.4 3.2
3.2
ghci> max 100 101
101



blog comments powered by Disqus