Skip to content

Instantly share code, notes, and snippets.

@rajeakshay
Created March 31, 2016 05:01
Show Gist options
  • Save rajeakshay/81b9a8fa0d31c27f9645dd28681cf888 to your computer and use it in GitHub Desktop.
Save rajeakshay/81b9a8fa0d31c27f9645dd28681cf888 to your computer and use it in GitHub Desktop.
Introduction to Haskell - Notes from the 1 hour talk by Greg Hale (@imalsogreg) at Northeastern University.
module Main where
-- This is how you write a comment in Haskell
import Prelude hiding (length) -- Hide length function to define our own later
import Data.List ()
import Data.Char -- required for toUpper
-- Defining your own data types
data MyBool = MyTrue
| MyFalse
| MaybeFalse Int
deriving (Show)
-- ^^^ Derive from Show class so that MyBool can be converted to character string for I/O
-- Think of toString method of every object in Java
-- On the ghci REPL, :t MyTrue will show the data type as MyBool
-- Functions need to specify contracts, unlike Racket/Scheme
suc :: Int -> Int
suc x = x + 25
-- suc 10 will return 35
-- Defining a generic List containing items of some type 'a'
-- 'a' can be any type, even a function
data List a = Nil
| Cons a (List a)
deriving (Show)
-- Using recursion
length :: List a -> Int
length Nil = 0
length (Cons _ l) = 1 + length l
-- ^^^ Here _ is a placeholder for head of the List, which can be any 'a'.
-- l is the rest of the List.
-- We can do something like this -
m = Cons length (Cons length Nil)
-- ^^^ A list of functions.
-- Defining a function in terms of other functions
myfunction :: [Char] -> [Char]
myfunction = map toUpper
-- myfunction "hello" will produce "HELLO"
-- map iterates all Char in the string and applies toUpper to each of them.
-- Try :t (1 + 10) on REPL, output is (1 + 10) :: Num a => a
-- 'Num a =>' is called as a constraint.
-- Implementing a binary search tree
data Tree a = Leaf a
| Node a (Tree a) (Tree a)
search :: (Eq a, Ord a) => a -> Tree a -> Bool
search x (Leaf y) = y == x
search x (Node y l r)
| x < y = search x l
| x > y = search x r
| x == y = True
example :: Tree Char
example = Node 'c' (Leaf 'a') (Leaf 'd')
-- search 'a' example returns True
-- search 'b' example returns False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment