Haskell - Function Evaluation - haskell

I am confused about when Haskell evaluates functions, compared to when it just returns the function itself. I was taught that pattern matching drives function evaluation, but then I don't understand why
f :: Int -> Int
f x = x+1
works. Does f add 1 to an integer, or does it return a function which adds 1 to an integer? Are these two the same thing? There is no pattern matching as far as I can tell, so I'm not sure why it gets evaluated.
Another question: suppose I want to make an 8x8 list that contains all 0's, except the first row contains the numbers 1,2,3,4,5,6,7,8 instead. Is there any way I could initialize it to all 0's first and then change the first row to [1..8]? I understand that it's not idiomatic to make sequential code like this, so is there a better way to do it, hopefully without using do blocks?
Finally, I am also confused about the let and where syntax. Suppose that in the middle of a function definition, I say temp = x + 1. How is this different from saying let temp = x + 1 or ...temp where temp = x + 1? In each of these cases, does temp have type Int or Int -> Int? Why do people use do with let so often?

This certainly was a collection of questions.
Firstly, about evaluation, Haskell is lazy. It will evaluate values as they are needed. This includes the fact that a function is not necessarily evaluated in its entirety. Pattern matching may drive evaluation in some cases, for instance in maybe either a Nothing or Just x must match, in order to find out what value is produced. But if you didn't demand the result in the first place, this matching was never needed.
f in your example is a function known as (+1), or more explicitly \x -> x + 1. Being a function, it must be applied to a value to produce another, and there is in fact a pattern; the argument x, having type Int. This works as a simple binding, but it could have been a constant value pattern like 1 instead. Here's an example:
fib :: Int -> Int
fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
The two first patterns give us our base cases.
An 8x8 grid of numbers is a matrix, not a list. Data.Array, Data.Matrix and Data.Vector provide types that can describe such things more accurately, and what you describe can be done. Data.Ix provides multidimensional indices and functions like Data.Vector.modify may perform updates in place without violating value immutability.
let bindings in expression and expression where bindings are mostly a matter of preference. let binding within a do block is a different matter. In your sample binding temp = x + 1, x must be bound from elsewhere, + is of type Num a => a -> a -> a, so both x and temp must be the same Num a. A function must take an argument, so this is just a value (though mathematically it's a function of x).
As for do with let, it's essentially a shorthand for adding another binding; you could write:
main = do
putStrLn "hello"
let word = "world"
putStrLn word
and it's equivalent to:
main = do
putStrLn "hello"
let word = "world" in do
putStrLn word
This provides a way to introduce a pure value mid-do, like <- introduces monadic ones.

Related

How to know the data type of a value of a sum type [duplicate]

What is pattern matching in Haskell and how is it related to guarded equations?
I've tried looking for a simple explanation, but I haven't found one.
EDIT:
Someone tagged as homework. I don't go to school anymore, I'm just learning Haskell and I'm trying to understand this concept. Pure out of interest.
In a nutshell, patterns are like defining piecewise functions in math. You can specify different function bodies for different arguments using patterns. When you call a function, the appropriate body is chosen by comparing the actual arguments with the various argument patterns. Read A Gentle Introduction to Haskell for more information.
Compare:
with the equivalent Haskell:
fib 0 = 1
fib 1 = 1
fib n | n >= 2
= fib (n-1) + fib (n-2)
Note the "n ≥ 2" in the piecewise function becomes a guard in the Haskell version, but the other two conditions are simply patterns. Patterns are conditions that test values and structure, such as x:xs, (x, y, z), or Just x. In a piecewise definition, conditions based on = or ∈ relations (basically, the conditions that say something "is" something else) become patterns. Guards allow for more general conditions. We could rewrite fib to use guards:
fib n | n == 0 = 1
| n == 1 = 1
| n >= 2 = fib (n-1) + fib (n-2)
There are other good answers, so I'm going to give you a very technical answer. Pattern matching is the elimination construct for algebraic data types:
"Elimination construct" means "how to consume or use a value"
"Algebraic data type", in addition to first-class functions, is the big idea in a statically typed functional language like Clean, F#, Haskell, or ML
The idea of algebraic data types is that you define a type of thing, and you say all the ways you can make that thing. As an example, let's define "Sequence of String" as an algebraic data type, with three ways to make it:
data StringSeq = Empty -- the empty sequence
| Cat StringSeq StringSeq -- two sequences in succession
| Single String -- a sequence holding a single element
Now, there are all sorts of things wrong with this definition, but as an example it's interesting because it provides constant-time concatenation of sequences of arbitrary length. (There are other ways to achieve this.) The declaration introduces Empty, Cat, and Single, which are all the ways there are of making sequences. (That makes each one an introduction construct—a way to make things.)
You can make an empty sequence without any other values.
To make a sequence with Cat, you need two other sequences.
To make a sequence with Single, you need an element (in this case a string)
Here comes the punch line: the elimination construct, pattern matching, gives you a way to scrutinize a sequence and ask it the question what constructor were you made with?. Because you have to be prepared for any answer, you provide at least one alternative for each constructor. Here's a length function:
slen :: StringSeq -> Int
slen s = case s of Empty -> 0
Cat s s' -> slen s + slen s'
Single _ -> 1
At the core of the language, all pattern matching is built on this case construct. However, because algebraic data types and pattern matching are so important to the idioms of the language, there's special "syntactic sugar" for doing pattern matching in the declaration form of a function definition:
slen Empty = 0
slen (Cat s s') = slen s + slen s'
slen (Single _) = 1
With this syntactic sugar, computation by pattern matching looks a lot like definition by equations. (The Haskell committee did this on purpose.) And as you can see in the other answers, it is possible to specialize either an equation or an alternative in a case expression by slapping a guard on it. I can't think of a plausible guard for the sequence example, and there are plenty of examples in the other answers, so I'll leave it there.
Pattern matching is, at least in Haskell, deeply tied to the concept of algebraic data types. When you declare a data type like this:
data SomeData = Foo Int Int
| Bar String
| Baz
...it defines Foo, Bar, and Baz as constructors--not to be confused with "constructors" in OOP--that construct a SomeData value out of other values.
Pattern matching is nothing more than doing this in reverse--a pattern would "deconstruct" a SomeData value into its constituent pieces (in fact, I believe that pattern matching is the only way to extract values in Haskell).
When there are multiple constructors for a type, you write multiple versions of a function for each pattern, with the correct one being selected depending on which constructor was used (assuming you've written patterns to match all possible constructions--which it's generally good practice to do).
In a functional language, pattern matching involves checking an argument against different forms. A simple example involves recursively defined operations on lists. I will use OCaml to explain pattern matching since it's my functional language of choice, but the concepts are the same in F# and Haskell, AFAIK.
Here is the definition of a function to compute the length of a list lst. In OCaml, an ``a listis defined recursively as the empty list[], or the structureh::t, wherehis an element of typea(abeing any type we want, such as an integer or even another list),tis a list (hence the recursive definition), and::` is the cons operator, which creates a new list out of an element and a list.
So the function would look like this:
let rec len lst =
match lst with
[] -> 0
| h :: t -> 1 + len t
rec is a modifier that tells OCaml that a function will call itself recursively. Don't worry about that part. The match statement is what we're focusing on. OCaml will check lst against the two patterns - empty list, or h :: t - and return a different value based on that. Since we know every list will match one of these patterns, we can rest assured that our function will return safely.
Note that even though these two patterns will take care of all lists, you aren't limited to them. A pattern like h1 :: h2 :: t (matching all lists of length 2 or more) is also valid.
Of course, the use of patterns isn't restricted to recursively defined data structures, or recursive functions. Here is a (contrived) function to tell you whether a number is 1 or 2:
let is_one_or_two num =
match num with
1 -> true
| 2 -> true
| _ -> false
In this case, the forms of our pattern are the numbers themselves. _ is a special catch-all used as a default case, in case none of the above patterns match.
Pattern matching is one of those painful operations that is hard to get one's head around if you come from procedural programming background. I find it hard to get into because the same syntax used to create a data structure can be used for matching.
In F# you can use the cons operator :: to add an element to the beginning of a list like so:
let a = 1 :: [2;3]
//val a : int list = [1; 2; 3]
Similarly you can use the same operator to split the list up like so:
let a = [1;2;3];;
match a with
| [a;b] -> printfn "List contains 2 elements" //will match a list with 2 elements
| a::tail -> printfn "Head is %d" a //will match a list with 2 or more elements
| [] -> printfn "List is empty" //will match an empty list

Why am I receiving this syntax error - possibly due to bad layout?

I've just started trying to learn haskell and functional programming. I'm trying to write this function that will convert a binary string into its decimal equivalent. Please could someone point out why I am constantly getting the error:
"BinToDecimal.hs":19 - Syntax error in expression (unexpected `}', possibly due to bad layout)
module BinToDecimal where
total :: [Integer]
total = []
binToDecimal :: String -> Integer
binToDecimal a = if (null a) then (sum total)
else if (head a == "0") then binToDecimal (tail a)
else if (head a == "1") then total ++ (2^((length a)-1))
binToDecimal (tail a)
So, total may not be doing what you think it is. total isn't a mutable variable that you're changing, it will always be the empty list []. I think your function should include another parameter for the list you're building up. I would implement this by having binToDecimal call a helper function with the starting case of an empty list, like so:
binToDecimal :: String -> Integer
binToDecimal s = binToDecimal' s []
binToDecimal' :: String -> [Integer] -> Integer
-- implement binToDecimal' here
In addition to what #Sibi has said, I would highly recommend using pattern matching rather than nested if-else. For example, I'd implement the base case of binToDecimal' like so:
binToDecimal' :: String -> [Integer] -> Integer
binToDecimal' "" total = sum total -- when the first argument is the empty string, just sum total. Equivalent to `if (null a) then (sum total)`
-- Include other pattern matching statements here to handle your other if/else cases
If you think it'd be helpful, I can provide the full implementation of this function instead of giving tips.
Ok, let me give you hints to get you started:
You cannot do head a == "0" because "0" is String. Since the type of a is [Char], the type of head a is Char and you have to compare it with an Char. You can solve it using head a == '0'. Note that "0" and '0' are different.
Similarly, rectify your type error in head a == "1"
This won't typecheck: total ++ (2^((length a)-1)) because the type of total is [Integer] and the type of (2^((length a)-1)) is Integer. For the function ++ to typecheck both arguments passed to it should be list of the same type.
You are possible missing an else block at last. (before the code binToDecimal (tail a))
That being said, instead of using nested if else expression, try to use guards as they will increase the readability greatly.
There are many things we can improve here (but no worries, this is perfectly normal in the beginning, there is so much to learn when we start Haskell!!!).
First of all, a string is definitely not an appropriate way to represent a binary, because nothing prevents us to write "éaldkgjasdg" in place of a proper binary. So, the first thing is to define our binary type:
data Binary = Zero | One deriving (Show)
We just say that it can be Zero or One. The deriving (Show) will allow us to have the result displayed when run in GHCI.
In Haskell to solve problem we tend to start with a more general case to dive then in our particular case. The thing we need here is a function with an additional argument which holds the total. Note the use of pattern matching instead of ifs which makes the function easier to read.
binToDecimalAcc :: [Binary] -> Integer -> Integer
binToDecimalAcc [] acc = acc
binToDecimalAcc (Zero:xs) acc = binToDecimalAcc xs acc
binToDecimalAcc (One:xs) acc = binToDecimalAcc xs $ acc + 2^(length xs)
Finally, since we want only to have to pass a single parameter we define or specific function where the acc value is 0:
binToDecimal :: [Binary] -> Integer
binToDecimal binaries = binToDecimalAcc binaries 0
We can run a test in GHCI:
test1 = binToDecimal [One, Zero, One, Zero, One, Zero]
> 42
OK, all fine, but what if you really need to convert a string to a decimal? Then, we need a function able to convert this string to a binary. The problem as seen above is that not all strings are proper binaries. To handle this, we will need to report some sort of error. The solution I will use here is very common in Haskell: it is to use "Maybe". If the string is correct, it will return "Just result" else it will return "Nothing". Let's see that in practice!
The first function we will write is to convert a char to a binary. As discussed above, Nothing represents an error.
charToBinary :: Char -> Maybe Binary
charToBinary '0' = Just Zero
charToBinary '1' = Just One
charToBinary _ = Nothing
Then, we can write a function for a whole string (which is a list of Char). So [Char] is equivalent to String. I used it here to make clearer that we are dealing with a list.
stringToBinary :: [Char] -> Maybe [Binary]
stringToBinary [] = Just []
stringToBinary chars = mapM charToBinary chars
The function mapM is a kind of variation of map which acts on monads (Maybe is actually a monad). To learn about monads I recommend reading Learn You a Haskell for Great Good!
http://learnyouahaskell.com/a-fistful-of-monads
We can notice once more that if there are any errors, Nothing will be returned.
A dedicated function to convert strings holding binaries can now be written.
binStringToDecimal :: [Char] -> Maybe Integer
binStringToDecimal = fmap binToDecimal . stringToBinary
The use of the "." function allow us to define this function as an equality with another function, so we do not need to mention the parameter (point free notation).
The fmap function allow us to run binToDecimal (which expect a [Binary] as argument) on the return of stringToBinary (which is of type "Maybe [Binary]"). Once again, Learn you a Haskell... is a very good reference to learn more about fmap:
http://learnyouahaskell.com/functors-applicative-functors-and-monoids
Now, we can run a second test:
test2 = binStringToDecimal "101010"
> Just 42
And finally, we can test our error handling system with a mistake in the string:
test3 = binStringToDecimal "102010"
> Nothing

Why is there only one non-strict function from Int to Int?

According to this article on denotational semantics for Haskell there is only one non-strict (non-bottom prreserving) function from Int to Int.
to quote:
it happens that there is only one prototype of a non-strict function of type Integer -> Integer:
one x = 1
Its variants are constk x = k for every concrete number k. Why are these the only ones possible? Remember that one n can be no less defined than one ⊥. As Integer is a flat domain, both must be equal.
Essentially it says that the only non-strict functions of that type signature can only be the constant functions. I don't follow this argument. I'm also unsure what is meant by a flat domain, the rest of the article leads to believe that it simply means that the poset of values has only one node: bottom.
Does something similar occur for function going from A->A, or A->B? That is they must be constant functions?
Any function on Integer that is not const k for some constant k must inspect its argument. You can't partially inspect an Integer, which might be is what is meant by it being a "flat domain". This is a consequence of how the semantics of Integer are defined in the Haskell specs, not something that follows from the core language's semantics.
By contrast, infinitely many non-strict functions of type [a] -> [a] exist for every type a, e.g. take1:
take1 (x:_) = [x]
To show non-strictness, define
ones = 1 : ones
In terms of denotational semantics, [[ones]] = ⊥. But take1 ones evaluates to [1], so take1 is non-strict. So are take2 (x:y:_) = [x,y], take10, etc.
If you want non-strict, non-constant functions on integers, you need a different representation of the integers than Integer, e.g.:
data Bit = Zero | One
newtype BinaryInt = I [Bit]
If we interpret the list in an I as a "little-endian" binary integer, then the function
mod2 (I []) = I []
mod2 (I (lsb:_)) = I [lsb]
is non-strict.
The intuition is that a lazy function can't inspect its argument here without forcing it (and hence become strict). If you don't inspect your argument you have to be const
The real answer in monotonicity. If you think of semantic domains as posets where the ordering relationship is one of "defined-ness", all functions are order preserving. Why? Since all bottoms are created equal, and looping forever is the same thing as bottom, a non monotonic function would be one that solves the halting problem.
Okay, so why does that imply it const creates the only lazy functions? Well, say pick an arbitrary function f such that
f :: Integer -> Integer
f ⊥ = y
since ⊥ <= x for all x, it must be that y <= f x. If y is a non bottom value, then the only solution to that inequality is f x = y
Edit: The reason why this argument holds for types like Integer and Bool but not for types like [a] is the last step: Integer in a sense only has a single ⊥ in it. That is, all Integers are equally defined except for ⊥. On the other hand, ⊥ < (⊥:⊥) while (⊥:⊥) < (⊥:[]) and (⊥:⊥) < (⊥:(⊥:⊥)) < (⊥:(⊥:(⊥:⊥))) < ... whats more, (⊥:⊥) < ('a':⊥). That is, the semantic domain of [a] is rich enough that y <= f x with y =/= ⊥ does not imply that f x = y.

Loop through a set of functions with Haskell

Here's a simple, barebones example of how the code that I'm trying to do would look in C++.
while (state == true) {
a = function1();
b = function2();
state = function3();
}
In the program I'm working on, I have some functions that I need to loop through until bool state equals false (or until one of the variables, let's say variable b, equals 0).
How would this code be done in Haskell? I've searched through here, Google, and even Bing and haven't been able to find any clear, straight forward explanations on how to do repetitive actions with functions.
Any help would be appreciated.
Taking Daniels comment into account, it could look something like this:
f = loop init_a init_b true
where
loop a b True = loop a' b' (fun3 a' b')
where
a' = fun1 ....
b' = fun2 .....
loop a b False = (a,b)
Well, here's a suggestion of how to map the concepts here:
A C++ loop is some form of list operation in Haskell.
One iteration of the loop = handling one element of the list.
Looping until a certain condition becomes true = base case of a function that recurses on a list.
But there is something that is critically different between imperative loops and functional list functions: loops describe how to iterate; higher-order list functions describe the structure of the computation. So for example, map f [a0, a1, ..., an] can be described by this diagram:
[a0, a1, ..., an]
| | |
f f f
| | |
v v v
[f a0, f a1, ..., f an]
Note that this describes how the result is related to the arguments f and [a0, a1, ..., an], not how the iteration is performed step by step.
Likewise, foldr f z [a0, a1, ..., an] corresponds to this:
f a0 (f a1 (... (f an z)))
filter doesn't quite lend itself to diagramming, but it's easy to state many rules that it satisfies:
length (filter pred xs) <= length xs
For every element x of filter pred xs, pred x is True.
If x is an element of filter pred xs, then x is an element of xs
If x is not an element of xs, then x is not an element of filter pred xs
If x appears before x' in filter pred xs, then x appears before x' in xs
If x appears before x' in xs, and both x and x' appear in filter pred xs, then x appears before x' in filter pred xs
In a classic imperative program, all three of these cases are written as loops, and the difference between them comes down to what the loop body does. Functional programming, on the contrary, insists that this sort of structural pattern does not belong in "loop bodies" (the functions f and pred in these examples); rather, these patterns are best abstracted out into higher-order functions like map, foldr and filter. Thus, every time you see one of these list functions you instantly know some important facts about how the arguments and the result are related, without having to read any code; whereas in a typical imperative program, you must read the bodies of loops to figure this stuff out.
So the real answer to your question is that it's impossible to offer an idiomatic translation of an imperative loop into functional terms without knowing what the loop body is doing—what are the preconditions supposed to be before the loop runs, and what the postconditions are supposed to be when the loop finishes. Because that loop body that you only described vaguely is going to determine what the structure of the computation is, and different such structures will call for different higher-order functions in Haskell.
First of all, let's think about a few things.
Does function1 have side effects?
Does function2 have side effects?
Does function3 have side effects?
The answer to all of these is a resoundingly obvious YES, because they take no inputs, and presumably there are circumstances which cause you to go around the while loop more than once (rather than def function3(): return false). Now let's remodel these functions with explicit state.
s = initialState
sentinel = true
while(sentinel):
a,b,s,sentinel = function1(a,b,s,sentinel)
a,b,s,sentinel = function2(a,b,s,sentinel)
a,b,s,sentinel = function3(a,b,s,sentinel)
return a,b,s
Well that's rather ugly. We know absolutely nothing about what inputs each function draws from, nor do we know anything about how these functions might affect the variables a, b, and sentinel, nor "any other state" which I have simply modeled as s.
So let's make a few assumptions. Firstly, I am going to assume that these functions do not directly depend on nor affect in any way the values of a, b, and sentinel. They might, however, change the "other state". So here's what we get:
s = initState
sentinel = true
while (sentinel):
a,s2 = function1(s)
b,s3 = function2(s2)
sentinel,s4 = function(s3)
s = s4
return a,b,s
Notice I've used temporary variables s2, s3, and s4 to indicate the changes that the "other state" goes through. Haskell time. We need a control function to behave like a while loop.
myWhile :: s -- an initial state
-> (s -> (Bool, a, s)) -- given a state, produces a sentinel, a current result, and the next state
-> (a, s) -- the result, plus resultant state
myWhile s f = case f s of
(False, a, s') -> (a, s')
(True, _, s') -> myWhile s' f
Now how would one use such a function? Well, given we have the functions:
function1 :: MyState -> (AType, MyState)
function2 :: MyState -> (BType, MyState)
function3 :: MyState -> (Bool, MyState)
We would construct the desired code as follows:
thatCodeBlockWeAreTryingToSimulate :: MyState -> ((AType, BType), MyState)
thatCodeBlockWeAreTryingToSimulate initState = myWhile initState f
where f :: MyState -> (Bool, (AType, BType), MyState)
f s = let (a, s2) = function1 s
(b, s3) = function2 s2
(sentinel, s4) = function3 s3
in (sentinel, (a, b), s4)
Notice how similar this is to the non-ugly python-like code given above.
You can verify that the code I have presented is well-typed by adding function1 = undefined etc for the three functions, as well as the following at the top of the file:
{-# LANGUAGE EmptyDataDecls #-}
data MyState
data AType
data BType
So the takeaway message is this: in Haskell, you must explicitly model the changes in state. You can use the "State Monad" to make things a little prettier, but you should first understand the idea of passing state around.
Lets take a look at your C++ loop:
while (state == true) {
a = function1();
b = function2();
state = function3();
}
Haskell is a pure functional language, so it won't fight us as much (and the resulting code will be more useful, both in itself and as an exercise to learn Haskell) if we try to do this without side effects, and without using monads to make it look like we're using side effects either.
Lets start with this structure
while (state == true) {
<<do stuff that updates state>>
}
In Haskell we're obviously not going to be checking a variable against true as the loop condition, because it can't change its value[1] and we'd either evaluate the loop body forever or never. So instead, we'll want to be evaluating a function that returns a boolean value on some argument:
while (check something == True) {
<<do stuff that updates state>>
}
Well, now we don't have a state variable, so that "do stuff that updates state" is looking pretty pointless. And we don't have a something to pass to check. Lets think about this a bit more. We want the something to be checked to depend on what the "do stuff" bit is doing. We don't have side effects, so that means something has to be (or be derived from) returned from the "do stuff". "do stuff" also needs to take something that varies as an argument, or it'll just keep returning the same thing forever, which is also pointless. We also need to return a value out all this, otherwise we're just burning CPU cycles (again, with no side effects there's no point running a function if we don't use its output in some way, and there's even less point running a function repeatedly if we never use its output).
So how about something like this:
while check func state =
let next_state = func state in
if check next_state
then while check func next_state
else next_state
Lets try it in GHCi:
*Main> while (<20) (+1) 0
20
This is the result of applying (+1) repeatedly while the result is less than 20, starting from 0.
*Main> while ((<20) . length) (++ "zob") ""
"zobzobzobzobzobzobzob"
This is the result of concatenating "zob" repeatedly while the result's length is less than 20, starting from the empty string.
So you can see I've defined a function that is (sort of a bit) analogous to a while loop from imperative languages. We didn't even need dedicated loop syntax for it! (which is the real reason Haskell has no such syntax; if you need this kind of thing you can express it as a function). It's not the only way to do so, and experienced Haskell programmers would probably use other standard library functions to do this kind of job, rather than writing while.
But I think it's useful to see how you can express this kind of thing in Haskell. It does show that you can't translate things like imperative loops directly into Haskell; I didn't end up translating your loop in terms of my while because it ends up pretty pointless; you never use the result of function1 or function2, they're called with no arguments so they'd always return the same thing in every iteration, and function3 likewise always returns the same thing, and can only return true or false to either cause while to keep looping or stop, with no information resulting.
Presumably in the C++ program they're all using side effects to actually get some work done. If they operate on in-memory things then you need to translate a bigger chunk of your program at once to Haskell for the translation of this loop to make any sense. If those functions are doing IO then you'll need to do this in the IO monad in Haskell, for which my while function doesn't work, but you can do something similar.
[1] As an aside, it's worth trying to understand that "you can't change variables" in Haskell isn't just an arbitrary restriction, nor is it just an acceptable trade off for the benefits of purity, it is a concept that doesn't make sense the way Haskell wants you to think about Haskell code. You're writing down expressions that result from evaluating functions on certain arguments: in f x = x + 1 you're saying that f x is x + 1. If you really think of it that way rather than thinking "f takes x, then adds one to it, then returns the result" then the concept of "having side effects" doesn't even apply; how could something existing and being equal to something else somehow change a variable, or have some other side effect?
You should write a solution to your problem in a more functional approach.
However, some code in haskell works a lot like imperative looping, take for example state monads, terminal recursivity, until, foldr, etc.
A simple example is the factorial. In C, you would write a loop where in haskell you can for example write fact n = foldr (*) 1 [2..n].
If you've two functions f :: a -> b and g :: b -> c where a, b, and c are types like String or [Int] then you can compose them simply by writing f . b.
If you wish them to loop over a list or vector you could write map (f . g) or V.map (f . g), assuming you've done Import qualified Data.Vector as V.
Example : I wish to print a list of markdown headings like ## <number>. <heading> ## but I need roman numerals numbered from 1 and my list headings has type type [(String,Double)] where the Double is irrelevant.
Import Data.List
Import Text.Numeral.Roman
let fun = zipWith (\a b -> a ++ ". " ++ b ++ "##\n") (map toRoman [1..]) . map fst
fun [("Foo",3.5),("Bar",7.1)]
What the hell does this do?
toRoman turns a number into a string containing the roman numeral. map toRoman does this to every element of a loop. map toRoman [1..] does it to every element of the lazy infinite list [1,2,3,4,..], yielding a lazy infinite list of roman numeral strings
fst :: (a,b) -> a simply extracts the first element of a tuple. map fst throws away our silly Meow information along the entire list.
\a b -> "##" ++ show a ++ ". " ++ b ++ "##" is a lambda expression that takes two strings and concatenates them together within the desired formatting strings.
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] takes a two argument function like our lambda expression and feeds it pairs of elements from it's own second and third arguments.
You'll observe that zip, zipWith, etc. only read as much of the lazy infinite list of Roman numerals as needed for the list of headings, meaning I've number my headings without maintaining any counter variable.
Finally, I have declared fun without naming it's argument because the compiler can figure it out from the fact that map fst requires one argument. You'll notice that put a . before my second map too. I could've written (map fst h) or $ map fst h instead if I'd written fun h = ..., but leaving the argument off fun meant I needed to compose it with zipWith after applying zipWith to two arguments of the three arguments zipWith wants.
I'd hope the compiler combines the zipWith and maps into one single loop via inlining.

The meaning of ' in Haskell function name?

What is quote ' used for? I have read about curried functions and read two ways of defining the add function - curried and uncurried. The curried version...
myadd' :: Int -> Int -> Int
myadd' x y = x + y
...but it works equally well without the quote. So what is the point of the '?
The quote means nothing to Haskell. It is just part of the name of that function.
People tend to use this for "internal" functions. If you have a function that sums a list by using an accumulator argument, your sum function will take two args. This is ugly, so you make a sum' function of two args, and a sum function of one arg like sum list = sum' 0 list.
Edit, perhaps I should just show the code:
sum' s [] = s
sum' s (x:xs) = sum' (s + x) xs
sum xs = sum' 0 xs
You do this so that sum' is tail-recursive, and so that the "public API" is nice looking.
It is often pronounced "prime", so that would be "myadd prime". It is usually used to notate a next step in the computation, or an alternative.
So, you can say
add = blah
add' = different blah
Or
f x =
let x' = subcomputation x
in blah.
It just a habit, like using int i as the index in a for loop for Java, C, etc.
Edit: This answer is hopefully more helpful now that I've added all the words, and code formatting. :) I keep on forgetting that this is not a WYSIWYG system!
There's no particular point to the ' character in this instance; it's just part of the identifier. In other words, myadd and myadd' are distinct, unrelated functions.
Conventionally though, the ' is used to denote some logical evaluation relationship. So, hypothetical function myadd and myadd' would be related such that myadd' could be derived from myadd. This is a convention derived from formal logic and proofs in academia (where Haskell has its roots). I should underscore that this is only a convention, Haskell does not enforce it.
quote ' is just another allowed character in Haskell names. It's often used to define variants of functions, in which case quote is pronounced 'prime'. Specifically, the Haskell libraries use quote-variants to show that the variant is strict. For example: foldl is lazy, foldl' is strict.
In this case, it looks like the quote is just used to separate the curried and uncurried variants.
As said by others, the ' does not hold any meaning for Haskell itself. It is just a character, like the a letter or a number.
The ' is used to denote alternative versions of a function (in the case of foldl and foldl') or helper functions. Sometimes, you'll even see several ' on a function name. Adding a ' to the end of a function name is just much more concise than writing someFunctionHelper and someFunctionStrict.
The origin of this notation is in mathematics and physics, where, if you have a function f(x), its derivate is often denoted as f'(x).

Resources