Skip to content

Latest commit

 

History

History
82 lines (62 loc) · 2.26 KB

02.md

File metadata and controls

82 lines (62 loc) · 2.26 KB

Expressions and values

GHCI

ghc ships with an interactive shell called ghci. It is a convenient tool to try out things without editing and compiling a source file. Start ghci in a shell and get used to it by trying out every code snippet in the lecture.

Expressions and values

Expressions evaluate to a value. In Haskell everything is an expression. All computations are done by evaluating expressions.

Type the following expressions in ghci line by line. Try to guess the value they evaluate to before pressing enter.

not (False || True && True)
not False || True && True

1 + 2 * 10
2 ^ (div 9 2)

2^2 * pi
12.3 / 0.123

length ("hello " ++ "there!")
length "hello" + 10

[1,2,3] ++ [10,11,12]
[1..10] ++ [(-10)..(-1)]

Types

Every expression has a type. Expressions with a type that does not fit their environment are invalid. For example you can not multiply the value true with a number since multiplication expects two numeric operands and true is a boolean. Haskell is a statically typed language, which means that the type of an expression is checked by the compiler. Invalid expression types cause type errors during compilation.

You can use ghci to inspect the type of expressions by prefixing the expression with :t.

Prelude> :t True
True :: Bool

Check the type of all of the expressions in the previous block. Don't just type them in but try to guess the result. Some of them is going to be scary at first. Do not worry, you will understand all of them in a couple of days.

So far we did not specify the type of our expressions explicitly. We could get away with it because ghc tries to find out the types for us. This is called type inference. Every time we write an expression we can explicitly specify the type by postfixing the expression with :: typename.

Prelude> 2*10
20
Prelude> 2*(10 :: Int)
20
Prelude> 2*(10 :: Double)
20.0
Prelude> :t 10
10 :: Num a => a
Prelude> :t 10 :: Int
10 :: Int :: Int

Exercises

  • Write at least three expressions that has a type error in them. Try them out in ghci.
  • Add or remove explicit type notations to the following expression to resolve the type error. Note: Integers can not be divided with the / operator.
(10 :: Int) / 2