Pablo

Getting Started with Haskell

Haskell can be compiled and interpreted.

In Haskell the functions in Haskell are citizens of first class.

Comments are initialised with double hyphen symbol --

What do you need?

To run all the snippets of code you need the Haskell Platform It run on Windows, Mac and Linux.

Functions

  • No parentheses in functions needed
  • No parentheses in around conditionals
  • No need 'return'

Making Functions

mult a b = a * b

'mult' is the name of function.

'a' and 'b' are the parameters.

The body of the function are after the equal sign, 'a' multiplied for 'b'

Call Functions

Using the above code

mult 3 4
--mult a b

The function are called and assign the parameters, '3' for 'a' and '4' for 'b'

Functions with conditionals

posOrNeg x = 
	if x >= 0 
	then "Positive" 
	else "Negative"

-- or it can be like that

let posOrNeg x = if x >= 0 then "Positive" else "Negative"

Recursion (is used instaed for/while loops)

pow2 n = 
	if n == 0
	then 1
	else 2 * (pow2 (n-1))

-- other way:
let pow2 n = if n == 0 then 1 else 2 * (pow2 (n-1))

Let's do...

if the argument in the function pow2 is 0 this return a 1

(but) if the argument is another (different of zero) this function multiply per 2 the return of the function subtracting 1 to the argument. (n-1)

In other languages like Java it could have been used/needed a for loop

More Recursion

repeatString str n = 
	if n == 0
	then ""
	else str ++ (repeatString str (n-1))

-- other way is:
let repeatString str n = if n == 0 then "" else str ++ (repeatString str (n-1))

Calling this function.

repeatString "Notes" 3
          -- str    n

--"NotesNotesNotes"

The function return the last line in the box

All ok, but how it works?

  1. In the code the function receive the string(str) and the times(n), if n is equal to zero return "".
  2. If n is greater than zero is executed a concatenation of str with a recursive call to the main function, the parameter n of this are modified, 1 is subtracted to n.

Thx for read!