In Haskell, operators are an essential part of the language that make it both powerful and expressive. Whether you’re working with basic arithmetic, manipulating lists, or chaining functions, Haskell’s rich set of operators provides flexible ways to interact with different data types. In this guide, we’ll explore the major operators available in Haskell, grouped by category for easier navigation.
In Haskell, to create an operator you must use the following “operator symbols”:
! # $ % * + . / < = > ? \ ^ | : – ~
Conceptually, there is no difference between an operator and a function, and you can use backticks or parens to make one work like the other.
1. Arithmetic Operators
Haskell supports a set of common arithmetic operators for performing calculations on numerical types. Here are the main operators:
+
– Addition-
– Subtraction*
– Multiplication/
– Division (forFractional
types)^
– Power (forIntegral
exponents)^^
– Power (forFractional
exponents)**
– Power (forFloating
types)
Arithmetic Functions
div
– Integer divisionmod
– Modulus (remainder after division)quot
– Integer quotientrem
– Integer remainderabs
– Absolute valuesignum
– Sign of a number (-1
,0
, or1
)sqrt
– Square root (for floating-point numbers)min
– Takes two values that can be comparedmax
– Is similar tomin
, but it returns the larger of two comparable values.succ
– Takes a value and returns its “successor” (the next value)pred
– The opposite ofsucc
, returning the “predecessor” (previous value) of a given value.
These operators make it easy to perform basic mathematical operations, whether you’re working with integers, floating-point numbers, or fractional types.
2. Comparison Operators
Comparison operators allow you to compare values and make decisions based on the relationships between them. Haskell provides a full range of comparison operators:
==
– Equal to/=
– Not equal to<
– Less than>
– Greater than<=
– Less than or equal to>=
– Greater than or equal to
Comparison operators are essential for controlling program flow, especially when working with conditionals.
3. Boolean (Logical) Operators
Haskell offers Boolean operators that are used for combining or negating Boolean values (True
or False
):
&&
– Logical AND||
– Logical OR
Boolean Functions
not
– Logical NOT
Boolean operators are typically used in expressions that require multiple conditions to be true or false.
4. Bitwise Operators (for Bits
Type Class)
Bitwise operators operate at the binary level and are mainly used for low-level data manipulation, commonly with integers:
.&.
– Bitwise AND.|.
– Bitwise OR
Bitwise Functions
xor
– Bitwise XOR (exclusive OR)complement
– Bitwise complementshift
– Shift bits (left or right depending on sign)rotate
– Rotate bits (left or right depending on sign)setBit
– Set a specific bit to1
clearBit
– Clear a specific bit to0
complementBit
– Toggle a specific bittestBit
– Test if a specific bit is setbit
– Create a number with a single bit setbitSize
– Get the number of bits in a typeisSigned
– Check if a type is signedshiftL
– Shift bits to the leftshiftR
– Shift bits to the rightrotateL
– Rotate bits to the leftrotateR
– Rotate bits to the right
Bitwise operations are less common in day-to-day Haskell programming but are useful for more specialized applications, such as working with binary data.
5. List Operators
Lists are fundamental in Haskell, and these operators make list manipulation straightforward:
++
– List concatenation, combines two lists into one.!!
– List indexing (zero-based), retrieves an element at a specific position in the list.
List Functions
head
– Returns the first element of a list.tail
– Returns the list without its first element.length
– Returns the length of a list.null
– Checks if a list is empty.reverse
– Reverses a list.take
– Returns the first n elements of a list.takeWhile
– Takes elements from the beginning of a list while a condition isTrue
.drop
– Drops the first n elements of a list.dropWhile
– Drops elements from the beginning of a list while a condition isTrue
.sum
– Returns the sum of elements in a list.product
– Returns the product of elements in a list.elem
– Checks if an element is in a list.notElem
– Is the opposite ofelem
. It returnsTrue
if the value is not in the list, otherwise it returnsFalse
.init
– Takes a list and returns everything except its last element.cycle
– Takes a list and cycles it into an infinite list. If you just try to display the result, it will go on forever so you have to slice it off somewhere.repeat
– Takes an element and produces an infinite list of just that element. It’s like cycling a list with only one element.zip
– Takes two lists and then zips them together into one list by joining the matching elements into pairs.zipWith
– Applies a function to corresponding elements of two lists and returns a new list.unzip
– Transforms a list of pairs into a pair of lists.quicksort
– Takes a list of items that can be sorted. Their type is an instance of the Ord typeclass. Quicksort orders them.foldl
– Reduces a list from the left by applying a function. Takes an accumulator, a function, and a list.foldr
– Reduces a list from the right by applying a function. Takes an accumulator, a function, and a list.scanl
– Likefoldl
, but returns a list of successive reductions from the left.scanr
– Likefoldr
, but returns a list of successive reductions from the right.span
– Splits a list into two parts: elements that satisfy a condition and the rest.break
– Similar tospan
, but stops as soon as the condition isTrue
.map
– Applies a function to each element in a list.filter
– Returns a list of elements that satisfy a predicate.concat
– Concatenates a list of lists into a single list.concatMap
– Maps a function over a list and concatenates the results.maximum
– Finds the largest element in a list.minimum
– Finds the smallest element in a list.and
– Checks if all elements in a list areTrue
.or
– Checks if any element in a list isTrue
.all
– Checks if all elements satisfy a condition.any
– Checks if any element satisfies a condition.
These operators simplify common list tasks, like joining lists or accessing elements by index.
6. Function Operators
Function operators in Haskell provide shortcuts for chaining functions together and managing function application:
$
– Function application (low precedence), allows you to omit parentheses in nested expressions..
– Function composition, combines two functions so that the output of one function becomes the input of the next.
These operators make it easier to write clean, readable function chains.
7. Monadic Operators
Monadic operators help work with values wrapped in monadic contexts, a common pattern in Haskell for handling side effects or chaining computations:
>>
– Sequentially compose two actions, discarding the result of the first.>>=
– Bind operator: passes the result of a monadic computation to the next function.=<<
– Reverse bind: passes a monadic value to a function in reverse order.>=>
– Left-to-right function composition in monads (Kleisli composition).<=<
– Right-to-left function composition in monads (Kleisli composition).
Monadic operators are especially useful in structuring code that involves chaining actions, like I/O or state transformations.
8. Applicative and Functor Operators
Applicative and Functor operators allow for working with functions and values inside contexts, like Maybe
, Either
, or lists:
<$>
– Functor map (infix version offmap
), applies a function to the contents of a functor.<*>
– Applicative apply, applies a function in a context to a value in a context.<*
– Sequence actions, discarding the result of the second action.*>
– Sequence actions, discarding the result of the first action.<$
– Replace all elements in a Functor with the same value.<|>
– Alternative choice (used withAlternative
type class).<**>
– Apply in reverse order.
These operators come in handy for handling operations on values that are wrapped in specific contexts, keeping code concise and expressive.
9. Miscellaneous Operators
These operators don’t fit neatly into the previous categories but are often used in Haskell for various purposes:
!!
– List indexing (zero-based), retrieves an element at a specific position in the list.:
– Cons operator, adds an element to the front of a list.\\
– List difference, removes elements from the first list that appear in the second list.$!
– Strict function application, forces evaluation of the argument before applying the function.
Conclusion
Haskell’s operators are versatile tools that enable you to write concise, expressive, and powerful code. By understanding the purpose of each operator and the contexts in which they’re most useful, you can make the most of Haskell’s capabilities. This comprehensive guide should serve as a quick reference to navigate Haskell’s operators and understand their applications.
Leave a Reply