12/08/2018, 14:37

Continue with Functional Programming: Haskell

This time I think we will deal a bit with Haskel, try to have a feel of it characteristics, which is functional in a mathematical sense. We will go directly to function in Haskell. That's where we will spend most of the time with. I assume that you know how to install haskell. let's start ...

This time I think we will deal a bit with Haskel, try to have a feel of it characteristics, which is functional in a mathematical sense.

We will go directly to function in Haskell. That's where we will spend most of the time with.

I assume that you know how to install haskell.

let's start our terminal and begin gchi where we can test Haskell with console.

gchi

GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude>

There are many tutorials on Haskell on the web, and what we trying to do here is the get you to taste the unique style of Haskell by assuming that you used to code in imperative language such C++, Python, or Java before.

We define function like this:

triple x = 3 * x

triple is function name; x is parameter. Note that there is no parentheses. "=" sign is special here, which begin the definition of the function.

Let's try

triple 5
=> 15

Hakell does not change state. You cannot literally assign a value as the following:

x = 5
=> parse error on input=

Once it is assigned using let x = 5, you cannot change it to something else. Remember that this is the essence of functional programming.

x -> f(x)
x is passed into a function and return a value

But x itselt does not change. This has a serious implication, such that it can be used in theorem proving, but here we won't get into that.

Let's get a few more examples before we launch a hard one at the end. Here is another example using if and else statement.

operate x = if x `mod` 2 == 0 then x - 1 else x * 2

List comprehension

The definition of set such as:

S = { 3.x | x E N, x <= 20} is very useful in defining any set without having to explicitly write all the elements.

Here we can write the above expression by following Haskell code:

let s = [3*x | x <- [1..20]]
[3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60]

In console we use let to assign a variable. "|" is for telling the beginning of constraints and other conditions. we can have more than one conditions separated by ",".

We can even have a complicated expression such as this:

[[x, y, z, t, u, v] | x <- [1..10], y <- [1..10], z <- [1..10], t <- [1..10], u <- [1..10], v <- [1..10], y >= x, z >= y, t >= z, u >= t, v >= u, x + y + z + t + u + v <= 100, 5*x + 3*y + z - t - 3*u - 5*v <= 100 ] !! 500

[1,1,3,8,10,10]

If we realy need to             </div>
            
            <div class=

0