Basics

  The Haskell programming language has some key differences to most programming languages, mainly it's "purely functional" form, making it great for mathematical applications. We'll write Haskell code much like we'd write some math notations, such as putting the "-" signal within parenthesis for certain operations. If running bits of Haskell code on the shell, you must put ($ :set prompt "ghci> ") to keep the shell prompt short, and ($ :module + Data.Ratio) to add the module which allows functionality for rational numbers (floats).

  Important notations to keep in mind about Haskell mathematics:

  • - is an unary operator, meaning we must attribute it to some values by using parenthesis. 3 - 2 will output 1, but 3 + -2 will return an error. 3 + (-2) is the correct way to go, here.
  • Numbers cannot be interpreted as booleans, so "1 && 0" or "1 || True" are invalid operations.
  • When checking "is not equal", instead of the usual !=, we will use /=, as it's closer to regular mathematics.
  • Along that line, instead of using ! for logical negation, we will use "not", for example: not True -> False
  • the value for pi is already defined, we will simply use "pi" within operations.
  • Haskell functions do not need parentheses after it. On the line "exp 1", exp's argument is 1.
  • Enumeration within a list can be done with "..", automatically filling the rest of a list. Ex: [1..5] = [1, 2, 3, 4, 5]. The step can be determined by specifying the first two values, such as [1.0, 1.25..2.0] = [1.0, 1.25, 1.5, 1.75, 2.0]. The numbers can also decrease, and not reach the target value if the step goes over it, such as [20, 15..8] = [20, 15, 10]. Enumerating with floating points can produce unexpected effects, so it's best to specify the step or not use it at all. Also, if you use [1..] on the ghci prompt, for example, you will have an infinite list, with the code only stopping upon interrpution / killing / hitting C. It has its use case, but generally, be careful.
  • Concatenating two lists is done with ++. For example: [3,1,3] ++ [3,7] = [3,1,3,3,7].
  • An element can be added to the front of a list using :. For example: 1 : [2,3] = [1,2,3]. The other way around, however, does not work, as the first argument of : must be an element.

  Haskell handles strings similarly to C, such that:

  • Strings go around double quotes: "Haskell".
  • Characters like newline and tab are represented by \n and \t, respectively.
  • Strings can be defined as lists of individual characters. For example, let a = ['w', 'o', 'r', 'd'] defines "word" in the variable a. a == "word": True.
  • As strings are lists, list operations work on them, such as: 'a' : "bc" = "abc" (note that a single character uses single quotes: 'a'). We can also use "abc" ++ "def" = "abcdef".