Skip to content

Latest commit

 

History

History
197 lines (158 loc) · 3.52 KB

CODE_HASKELL.md

File metadata and controls

197 lines (158 loc) · 3.52 KB

Code Basics

A list of basics topics working with Haskell.

Commands:

  • ghci - run the package
  • :l - load file
  • :r - reload package
  • :q - close interpreter
Hello world
  • helloWorld.hs:
module HelloWorld where

-- Monad
main :: IO ()
main = putStrLn "Hello World"
  • Run program:
ghci helloWorld.hs
main
Sum a range of numbers
  • myLib.hs:
module MyLib (sumNumbers) where

-- Monad
sumNumbers :: IO ()
sumNumbers = print (sum [1..10])
  • Run program:
ghci myLib.hs
sumNumbers
Functions
hello name = "Hello, " ++ name
hello "Juan"
Types
-- 2 params and return data
f :: Int -> Int -> Int
f x y = x*y+x+y
f 2 3 -- 11
Lists
list = ["A", "B", "C"]
head list -- "A"
tail list -- ["B", "C"]
Anonymous functions
-- a function without a name (Lambda abstraction)
f = \x y -> x*y+x+y
f 2 3 -- 11
Higher-order functions
[2*x | x <- [0..10]]
-- [0, 2, 4, etc]
            
map :: (elm -> res) -> [elm] -> [res]
map (\x -> x*2+1) [1..10]

-- Free point style (Event delegation)
mul2 = \x -> x * 2
map mul2 [1..5]
I/O
  • io.hs:
greeting() = do
  name <- getLine
  eventName <- getLine
  putStrLn ("Hola" ++ name)
  putStrLn ("Espero " ++ eventName ++ " te guste")
  • Run program:
stack ghci
:l io.hs
greeting()
Recursion
  • recursion.hs:
-- State machines?
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter fn [] = []
myFilter fn (head:tail)
  | fn head = head : myFilter fn tail
  | otherwise = myFilter fn tail
  • Run program:
stack ghci
:l recursion.hs
myFilter (\x -> x > 3) [1, 2, 3, 4] # greater than 3
myFilter (>3) [1, 2, 3, 4]
Loops
  • loops.hs:
-- map
f x = x*(x+1)
lst = map f [1..10]

-- using prefix functions
div = (/)

-- reduce
resultLeft = foldl div 1 [1..10]

-- reduceRight
resultRight = foldr div 1 [1..10]

main = do
  print lst
  print resultLeft
  print resultRight
  • Run program:
stack runhaskell loops.hs
Currying
currying :: Int -> Int -> Int -> Int
currying x y z = x*y+z
currying 2 3 4 -- 10

-- manual example (not necessary in Haskell, currying works automatically)
currying'   = \x y z -> x*y+z
currying''  = \x -> (\y z -> x*y+z)
currying''' = \x -> (\y -> (\z -> x*y+z))

Credits