Basic Syntax#
-- Single line comment
{- Multi-line
comment -}
Function Definition#
functionName :: Type -> Type -> ReturnType
functionName param1 param2 = expression
Let Expressions#
Where Clauses#
function param =
result
where
intermediateValue = someCalculation
result = finalCalculation intermediateValue
Data Types#
Basic Types#
Int
: IntegerInteger
: Arbitrary precision integerFloat
: Single-precision floating pointDouble
: Double-precision floating pointBool
: Boolean (True or False)Char
: Unicode characterString
: 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 elementtail
: All but first elementinit
: All but last elementlast
: Last elementlength
: Number of elementsreverse
: Reverse the listtake n
: First n elementsdrop n
: Remove first n elementselem
: 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 comparisonOrd
: OrderingShow
: Convert to StringRead
: Parse from StringNum
: Numeric operationsFunctor
: Mappable structuresApplicative
: Applicative functorsMonad
: 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