As with Python, instructions are typed directly into the console and, when Enter is pressed, the instruction is executed. As you are (probably) required to do by law, try good old “Hello, World!”:
putStrLn "Hello, World!"
Note that the prompt is prefixed with the word Prelude to let you know that the interpreter has imported a standard library. This prompt can grow longer when additional modules are loaded but we’ll cross that bridge when we come to it. Functional Programming often involves a lot of Maths so try out a few simple calculations:
Prelude> 10/2 5.0 Prelude> 3+2 5 Prelude> 100*3 300 Prelude> 5*-2 :12:2: Not in scope: ‘*-’
Negative values have to be enclosed in brackets otherwise you get the error above (telling you it doesn’t recognise the operator *-). So this works as intended:
Prelude> 5*(-2) -10
White space can be left in or taken out:
Prelude> 6+4 10 Prelude> 6 + 4 10 Prelude> 6 + -4 :17:1: Precedence parsing error cannot mix ‘+’ [infixl 6] and prefix `-' [infixl 6] in the same infix expression Prelude>
Again, brackets need to be used to enclose negative numbers but note the different error message. Haskell lets you write expression in prefix form (hence the text in the error message) if the operator is enclosed with some brackets:
Prelude> 6 + 4 10 Prelude> (+) 6 4 10 Prelude> 6 + (-4) 2 Prelude> (+) 6 (-4) 2
Boolean logic is similar to other languages except True is true and 1 is not true! So we have to use the word True with a capital letter at the front. Logical operators are &&, || and not:
Prelude> True && True True Prelude> True || False True Prelude> True && 1 :29:9: No instance for (Num Bool) arising from the literal ‘1’ In the second argument of ‘(&&)’, namely ‘1’ In the expression: True && 1 In an equation for ‘it’: it = True && 1
Relational operators are similar to most languages apart from ‘is not equal to’:
Prelude> 2 > 3 False Prelude> 3 >= 2 True Prelude> 3 /= 3 False
Lists are used a lot in Functional programs and are denoted by square brackets. They can empty or as long as you like but they must all be of the same data type. A string data type is defined differently than just a single character (eg. “string” and ‘c’). As expected a list of characters is also a string:
Prelude> ["list", "of", "strings"] ["list","of","strings"] Prelude> ['c', 'h', 'a', 'r', 's'] "chars"
Lists (and by extension, strings) can be concatenated using ++ for example:
Prelude> [10,9,8] ++ [7,6,5] [10,9,8,7,6,5] Prelude> "Hi " ++ "there" "Hi there"
An additional operator is used to add something to the head of the list:
Prelude> 11 : [10,9,8] [11,10,9,8]
We can also read a list element by referring to its index value using !! where 0 is the first element:
Prelude> "ABCDEF" !! 2 'C'
These are only some of the basics that will be used regularly. With some examples we will cover other nuances but these will be explained at a later point.