I'm new to Haskell and, in general, to functional programming, and I'm a bit uncomfortable with its syntax.
In the following code what does the =>
denote? And also (Num a, Ord a)
?
loop :: (Num a, Ord a) => a -> (t -> t) -> t -> t
=> separates two parts of a type signature: On the left, typeclass constraints. On the right, the actual type.
The @ Symbol is used to both give a name to a parameter and match that parameter against a pattern that follows the @ . It's not specific to lists and can also be used with other data structures.
It's merely an infix synonym for fmap , so you can write e.g. Prelude> (*2) <$> [1.. 3] [2,4,6] Prelude> show <$> Just 11 Just "11" Like most infix functions, it is not built-in syntax, just a function definition. But functors are such a fundamental tool that <$> is found pretty much everywhere.
The ++ operator is the list concatenation operator which takes two lists as operands and "combine" them into a single list.
This is a typeclass constraint; (Num a, Ord a) => ...
means that loop
works with any type a
that is an instance of the Num
and Ord
typeclasses, corresponding to numeric types and ordered types respectively. Basically, you can think of loop
as having the type on the right hand side of the =>
, except that a
is required to be an instance of Num
and Ord
.
You can think of typeclasses as basically similar to OOP interfaces (but they're not the same thing!) — they encapsulate a set of definitions which any instance must support, and generic code can be written using these definitions. For instance, Num
includes numeric operations like addition and multiplication, while Ord
includes less than, greater than, and so on.
For more information on typeclasses, see this introduction from Learn You a Haskell.
=>
separates two parts of a type signature:
So you can think of (Num a, Ord a) => a -> (t -> t) -> t -> t
as meaning "the type is a -> (t -> t) -> t -> t
and also there must be a Num
instance for a
and an Ord
instance for a
".
For more on typeclasses see http://www.learnyouahaskell.com/types-and-typeclasses
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With