Haskell Walkthrough – I

Learn you a Haskell for great good

Started checking out Haskell recently. I chose the Learn you a Haskell for great good book as my guide.

Language philosophy

Purely functional, which basically means the following:

  • No side effects: Function does one thing only. If you give it the same input it will give you the same output. Function always returns a value
  • Lazy: Haskell wont evaluate functions until it needs to show a result. This allows for infinite data structures since only the parts needed are actually computed
  • Statically typed: Compiler is aware of the types
  • Type inference: No need to explicitly specify each type. Compiler figures it out

Quick Functions

No brackets. Example:
*Main> div 50 10
Known as a Prefix functions. Can also be written as:
*Main> 50 `div` 10
Known as Infix function.

Quick Lists


Prelude> let a = [1,2,3,4]
Prelude> a ++ [5,6]

Cons operator

Note that the value of a is unchanged

Index operator

Prelude> [1,2,3,4] !! 0

List comprehension

Inspired by mathematical set comprehension. Reflected in the syntax
{ 2*x | x E N, x <= 5}

Main> [2*x | x ← [1..10], x `mod` 2 == 0]
[4, 8, 12, 16, 18 ,20]

The condition after the comma is a predicate. You can have multiple predicates separated by commas. When drawing values from several lists, every combination of elements from these lists is reflected in the resulting list

Main> [(x,y)|x ← [“Good”,”Bad”], y ← [“Apple”,”Cat”]]

Moral of the story

You start with a certain set of candidate solutions, and successively apply transformations and filters to them until you’ve narrowed the possibilities down to the one solution (or several solutions) that you’re after.

This entry was posted in Cool stuff, Tech bits and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s