Basic Syntax

Comments

-- Single line comment
{- Multi-line
   comment -}

Function Definition

functionName :: Type -> Type -> ReturnType
functionName param1 param2 = expression

Let Expressions

let x = 5
    y = 6
in x + y

Where Clauses

function param =
    result
    where
        intermediateValue = someCalculation
        result = finalCalculation intermediateValue

Data Types

Basic Types

  • Int: Integer
  • Integer: Arbitrary precision integer
  • Float: Single-precision floating point
  • Double: Double-precision floating point
  • Bool: Boolean (True or False)
  • Char: Unicode character
  • String: List of characters

Lists

[1, 2, 3, 4]  -- List of integers
['a', 'b', 'c']  -- List of characters (String)

Tuples

(1, "hello")  -- Tuple of Int and String
(True, 42, "answer")  -- Triple

Type Aliases

type Name = String
type Age = Int
type Person = (Name, Age)

Algebraic Data Types

data Bool = False | True
data Maybe a = Nothing | Just a
data List a = Nil | Cons a (List a)

Control Structures

If-Then-Else

if condition
    then expression1
    else expression2

Pattern Matching

factorial 0 = 1
factorial n = n * factorial (n - 1)

Guards

abs n
    | n < 0     = -n
    | otherwise = n

Case Expressions

case expression of
    pattern1 -> result1
    pattern2 -> result2
    _        -> defaultResult

List Operations

List Comprehensions

[x^2 | x <- [1..10], even x]

Common Functions

  • head: First element
  • tail: All but first element
  • init: All but last element
  • last: Last element
  • length: Number of elements
  • reverse: Reverse the list
  • take n: First n elements
  • drop n: Remove first n elements
  • elem: Check if element is in list

Higher-Order Functions

Map

map (*2) [1, 2, 3]  -- [2, 4, 6]

Filter

filter even [1..10]  -- [2, 4, 6, 8, 10]

Fold

foldl (+) 0 [1, 2, 3]  -- 6
foldr (:) [] [1, 2, 3]  -- [1, 2, 3]

Type Classes

Common Type Classes

  • Eq: Equality comparison
  • Ord: Ordering
  • Show: Convert to String
  • Read: Parse from String
  • Num: Numeric operations
  • Functor: Mappable structures
  • Applicative: Applicative functors
  • Monad: Monadic operations

Type Class Instance

instance Show MyType where
    show x = "MyType: " ++ (show $ getValue x)

IO Operations

Basic IO

main :: IO ()
main = do
    putStrLn "Hello, what's your name?"
    name <- getLine
    putStrLn $ "Nice to meet you, " ++ name ++ "!"

File IO

import System.IO

main = do
    handle <- openFile "file.txt" ReadMode
    contents <- hGetContents handle
    putStr contents
    hClose handle