Basic Syntax
Table of Contents
1 Basic Syntax
1.1 Operators
1.1.1 Logic Operators
True || False ⇒ True True && False ⇒ False True == False ⇒ False True /= False ⇒ True (/=) is the operator for different
1.1.2 Powers
x^n for n an integral (understand Int or Integer) x**y for y any kind of number (Float for example)
1.1.3 Application Operator - $
The application operator $
makes code more readable and cleaner
since substitutes parenthesis. It is also useful in higher-order
situations, such as map ($ 0) xs
, or zipWith ($) fs xs
.
> f $ g $ h x = f (g (h x))
1.1.4 Misc. Operators
>>= bind >> then *> then -> to a -> b: a to b <- bind (drawn from) (as it desugars to >>=) <$> (f)map <$ map-replace by 0 <$ f: "f map-replace by 0" <*> ap(ply) (as it is the same as Control.Monad.ap) $ (none, just as " " [whitespace]) . pipe to a . b: "b pipe-to a" !! index ! index / strict a ! b: "a index b", foo !x: foo strict x <|> or / alternative expr <|> term: "expr or term" ++ concat / plus / append [] empty list : cons :: of type / as f x :: Int: f x of type Int \ lambda @ as go ll@(l:ls): go ll as l cons ls ~ lazy go ~(a,b): go lazy pair a, b _ Whatever Used in Pattern Matching
1.2 Defining Values and Types
> let b = 100 :: Float > let a = 100 :: Int > let c = 100 :: Double > > b 100.0 > :t b b :: Float > :t a a :: Int > :t c c :: Double > > let x = 100.2323 > :t x x :: Double > > let y = [1..10] > y [1,2,3,4,5,6,7,8,9,10] > > let z = [1, 2, 4, 5, 6] :: [Float] > :t z z :: [Float] > let k = [1.2, 1.3, 1.4, 1.5 ] > k [1.2,1.3,1.4,1.5] > > :t k k :: [Double]
1.3 Type System
- A type is a collection of related values.
- Typeclasses are sets of types.
- A class is a collection of types that support certain operations, called the methods of the class.
- Each expressions must have a valid type, which is calculated before to evaluating the expression by the Haskell compiler, it is called type inference;
- Haskell programs are type safe, since type errors can never occur during run time;
- Type inference detects a very large class of programming errors, and is one of the most powerful and useful features of Haskell.
Reference:
1.3.1 Basic Types
Char | 'a' / 'b' / 'c' | Char Type |
[Char] | "String" | String |
Bool | True / False | Boolean |
Int | 1, 2, 3, 4 | Integers in a finite range. -2^29 to (2^29 - 1) |
Integer | 1, 2, 3, 4 | Arbitrary Precision Integer |
Float | 1.0, 2.0, 3.0 | 32 bits float point |
Double | 1.0, 2.0, 3.0 | 64 bits float point |
(Int, Char) | (1, 'a') | Tuples, unlike lists elements can have different types. |
[a] | [1, 2, 3, 4] | List has the type [Int], [Char], [Double] |
Selected Numeric Types
Type | Description |
---|---|
Double | Double-precision floating point. A common choice for floating-point data. |
Float | Single-precision floating point. Often used when interfacing with C. |
Int | Fixed-precision signed integer; minimum range [-2^29..2^29-1]. Commonly used. |
Int8 | 8-bit signed integer |
Int16 | 16-bit signed integer |
Int32 | 32-bit signed integer |
Int64 | 64-bit signed integer |
Integer | Arbitrary-precision signed integer; range limited only by machine resources. Commonly used. |
Rational | Arbitrary-precision rational numbers. Stored as a ratio of two Integers. |
Word | Fixed-precision unsigned integer; storage size same as Int |
Word8 | 8-bit unsigned integer |
Word16 | 16-bit unsigned integer |
Word32 | 32-bit unsigned integer |
Word64 | 64-bit unsigned integer |
References:
- http://shuklan.com/haskell/lec03.html#/0/1
- http://shuklan.com/haskell/lec05.html
- http://book.realworldhaskell.org/read/using-typeclasses.html
Class | Class Instance |
---|---|
Num | Int, Integer, Nat, Float, Double, Complex |
Real | Int, Integer, Nat. Float, Double, Complex |
Fractional | Float, Double, Rational, Complex |
Integral | Int, Nat, Integer, Natural |
RealFrac | Float, Double, Rational, Complex |
Floating | Float, Double, Complex |
RealFloat | Float, Double, Complex |
1.3.2 Basic Type Classes
Eq | Equality Types |
Ord | Ordered Types |
Show | Showables Types |
Read | Readable Types |
Num | Numeric Types |
Enum | Enum Types |
Example Methods:
(==) :: (Eq a) => a -> a -> Bool (<) :: (Ord a) => a -> a -> Bool show :: (Show a) => a -> String read :: (Read a) => String -> a (*) :: (Num a) => a -> a -> a
Value --> Type --> Typeclass
Standard Typeclasses:
- Show: Representable as String
- Enum: Enumerable in a list
- Num: Usable as a number
- Ord: Used for things with a total order
1.3.3 Standard Haskell Types
Credit: The Haskell 98 Report - Predefined Types and Classes
Booleans
data Bool = False | True deriving (Read, Show, Eq, Ord, Enum, Bounded)
Characters and Strings
type String = [Char]
Lists
data [a] = [] | a : [a] deriving (Eq, Ord)
The Unit Datatype ()
data () = () deriving (Eq, Ord, Bounded, Enum, Read, Show)
Other Types
data Maybe a = Nothing | Just a deriving (Eq, Ord, Read, Show) data Either a b = Left a | Right b deriving (Eq, Ord, Read, Show) data Ordering = LT | EQ | GT deriving (Eq, Ord, Bounded, Enum, Read, Show)
1.3.4 Standard Haskell Classes
Credit: The Haskell 98 Report - Predefined Types and Classes
The Eq Class
class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x == y) x == y = not (x /= y)
The Ord Class
class (Eq a) => Ord a where compare :: a -> a -> Ordering (<), (<=), (>=), (>) :: a -> a -> Bool max, min :: a -> a -> a compare x y | x == y = EQ | x <= y = LT | otherwise = GT x <= y = compare x y /= GT x < y = compare x y == LT x >= y = compare x y /= LT x > y = compare x y == GT -- Note that (min x y, max x y) = (x,y) or (y,x) max x y | x <= y = y | otherwise = x min x y | x <= y = x | otherwise = y
The Read and Show Classes
type ReadS a = String -> [(a,String)] type ShowS = String -> String class Read a where readsPrec :: Int -> ReadS a readList :: ReadS [a] -- ... default decl for readList given in Prelude class Show a where showsPrec :: Int -> a -> ShowS show :: a -> String showList :: [a] -> ShowS showsPrec _ x s = show x ++ s show x = showsPrec 0 x "" -- ... default decl for showList given in Prelude
The Enum Class
class Enum a where succ, pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int enumFrom :: a -> [a] -- [n..] enumFromThen :: a -> a -> [a] -- [n,n'..] enumFromTo :: a -> a -> [a] -- [n..m] enumFromThenTo :: a -> a -> a -> [a] -- [n,n'..m] -- Default declarations given in Prelude
1.3.5 Numeric Types Conversion
fromInteger :: (Num a) => Integer -> a fromRational :: (Fractional a) => Rational -> a toInteger :: (Integral a) => a -> Integer toRational :: (RealFrac a) => a -> Rational fromIntegral :: (Integral a, Num b) => a -> b fromRealFrac :: (RealFrac a, Fractional b) => a -> b fromIntegral = fromInteger . toInteger fromRealFrac = fromRational . toRational
1.3.6 Haskell-Style Syntax for types:
Function g from type a to type b:
g :: a -> b
Function with two arguments and result of type a:
s :: a -> a -> a
Function f from a type a to type m b, a type m parametrized on type b
f :: a -> m b
A function h which takes as argument two functions of type a -> b and b -> c and returns a function of type a -> m b
h :: ( a -> b) -> (b -> c) -> ( a -> m b)
Credits: http://yannesposito.com/Scratch/en/blog/Haskell-the-Hard-Way/
x :: Int ⇔ x is of type Int x :: a ⇔ x can be of any type x :: Num a => a ⇔ x can be any type a such that a belongs to Num type class f :: a -> b ⇔ f is a function from a to b f :: a -> b -> c ⇔ f is a function from a to (b→c) f :: (a -> b) -> c ⇔ f is a function from (a→b) to c
1.4 Lists
1.4.1 Overview
Haskell lists are built from nils ([]) empty list, and cons (:).
[x0, x1, x2, x3, ..., xn-1, xn] = x0:x1:x2:x3:...:xn-1:xn:[]
1.4.2 Creating Lists
> [-4, 10, 20, 30.40] > let x = [-23, 40, 60, 89, 100] > x [-23,40,60,89,100] > [0..10] [0,1,2,3,4,5,6,7,8,9,10] > > [-4..10] [-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10] >
1.4.3 List Operations
Picking the nth element of a list.
> [1, 2, 3, 4, 5, 6] !! 2 3 > [1, 2, 3, 4, 5, 6] !! 3 4 > [1, 2, 3, 4, 5, 6] !! 0 1
> let lst = [-4..10] > lst [-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10]
First Element
> head [1, 2, 3, 4, 5] 1
Last Element
> last [1, 2, 3, 4, 5] 5
Maximum element
> maximum lst 10
Minimum element
> minimum lst -4
Reversing a list
> reverse [1, 2, 3, 4, 5] [5,4,3,2,1]
Sum of all elements
> sum lst 45
Product of all elements
> product lst 0
Adding an element to the begining of the list
> 20 : lst [20,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10]
Adding an element to end of the list
> lst ++ [20] [-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,20] >
Extract the elements after the head of a list, which must be non-empty.
- tail
- [a] -> [a] Source
> tail [1, 2, 3, 4, 5] [2,3,4,5]
Return all the elements of a list except the last one. The list must be non-empty.
- init
- [a] -> [a] Source
> init [1, 2, 3, 4, 5] [1,2,3,4] >
Make a new list containing just the first N elements from an existing list.
- take n xs
> take 5 lst [-4,-3,-2,-1,0]
Delete the first N elements from a list.
- drop n xs
> lst [-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10] > > drop 5 lst [1,2,3,4,5,6,7,8,9,10]
Split a list into two smaller lists (at the Nth position).
- splitAt n xs
-- (Returns a tuple of two lists.) > splitAt 5 lst ([-4,-3,-2,-1,0],[1,2,3,4,5,6,7,8,9,10]) >
TakeWhile, applied to a predicate p and a list xs, returns the longest prefix (possibly empty) of xs of elements that satisfy p:
- takeWhile
- (a -> Bool) -> [a] -> [a]
> takeWhile (< 3) [1,2,3,4,1,2,3,4] [1,2] > takeWhile (< 9) [1,2,3] [1,2,3] > takeWhile (< 0) [1,2,3] []
DropWhile p xs returns the suffix remaining after takeWhile p xs:
- dropWhile
- (a -> Bool) -> [a] -> [a] Source
> takeWhile (< 3) [1,2,3,4,1,2,3,4] [1,2] > takeWhile (< 9) [1,2,3] [1,2,3] > takeWhile (< 0) [1,2,3] [] > dropWhile (< 3) [1,2,3,4,5,1,2,3] [3,4,5,1,2,3] > dropWhile (< 9) [1,2,3] [] > dropWhile (< 0) [1,2,3] [1,2,3] >
Concating Nested Lists
> :t concat concat :: [[a]] -> [a] > concat [[1, 2], [], [233, 33], [1, 2, 3]] [1,2,233,33,1,2,3] > concat ["hello", " world", " Haskell", "FP"] "hello world HaskellFP" >
1.4.4 Chekings Lists
Check if a list is empty.
- null xs
> null [] True > null [1, 2, 3, 4, 5] False
Find out whether any list element passes a given test.
- any my_test xs
> any (>3) [1, 2, 3, 4, 5] True > any (>10) [1, 2, 3, 4, 5] False > > any (==3) [1, 2, 3, 4, 5] True > > any (==10) [1, 2, 3, 4, 5] False >
Check whether all list elements pass a given test.
- all my_test xs
> all (>3) [1, 2, 3, 4, 5] False > all (<10) [1, 2, 3, 4, 5] True > all (<10) [1, 2, 3, 4, 5, 20] False >
Check if elements belongs to the list.
- elem
- Eq a => a -> [a] -> Bool
> elem 1 [1,2,3] True > elem 4 [1,2,3] False >