Skip to content

Instantly share code, notes, and snippets.

@ryan-scott-dev
Created July 19, 2012 03:36
Show Gist options
  • Save ryan-scott-dev/3140575 to your computer and use it in GitHub Desktop.
Save ryan-scott-dev/3140575 to your computer and use it in GitHub Desktop.
Haskell Notes
=============
Haskell
=============
http://learnyouahaskell.com/
Great resource for learning Haskell
=============
Language
=============
'[Haskell is a] general-purpose purely functional programming language, with non-strict semantics and strong static typing.'
=============
Basic Usage
=============
'ghci' to launch interactive mode
'ghci :l my_file.hs' to load interactive mode with the functions from a file
Once in ghci, call ':quit' to exit
=============
Lists
=============
let farm_animals = ['cat', 'dog', 'sheep', 'cow']
Can't mix data types
e.g.
['cat', 3, 2, 1, 'baaa']
The keyword let is used to declare a variable
Can concatenate lists by using the ++ operator
[1,2,3,4] ++ [9,10,11,12]
results in [1, 2, 3, 4, 9, 10, 11, 12]
Can pre-pend a value to the list by using the : operator
5:[1, 2, 3, 4]
becomes [5, 1, 2, 3, 4]
Can return the element at index using !!
['1','2','3','4'] !! 2
returns '2'
Lists can also contain lists
[[1,2,3], [1,2,3], [1,2,3]]
Can compare contents in lexicographical order
[1,2,3] > [4,5,6]
false
[1,2,3] > [1,2]
true
Some functions to call on a list
head
- returns the first element
tail
- returns everything but the first
last
- returns the last element
init
- returns everything but the last element
http://s3.amazonaws.com/lyah/listmonster.png
length, null, reverse, take, drop, maximum, minimum, sum, product, elem
=============
List Ranges
=============
[1..5]
= [1,2,3,4,5]
['a'..'d']
= ['a', 'b','c','d']
[3,6..20]
=[3,6,9,12,15,18]
BUT DONT USE FLOAT!!!!
=============
List Comprehension
=============
[x*2 | x <- [1..10]]
= [2,4,6,8,10,12,14,16,18,20]
x comes from [1..10]
applies 'x*2' on every element
=============
Tuples
=============
(1, 2, 3)
- Better way of storing offset data than a list
- Is still statically typed!
- [(1,2),(8,11,5),(4,5)] is invalid type (expected tuple(t1, t2, t3))
- [('a', 1), ('b', 2), ('c', 3 )]
=============
Function Declarations
=============
e.g. doubleMe x = x + x
[function_name] [parameters] = [function_body]
=============
Pattern Matching
=============
factorial :: Integer -> Integer // Optional
factorial 0 = 1
factorial n = n * factorial (n - 1)
fib n = fibs (0,1) !! n
where fibs (a,b) = a : fibs (b,a+b)
=============
Syntax Differences
=============
'!=' doesn't exist, use '/=' instead
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment