domingo, 26 de abril de 2015

Introduction

I have always been fascinated by computer programming. My appetite was whetted ever since I was exposed to languages such as BCPL, C, Snobol, Lisp, Prolog and many more. In my efforts to sharpen my problem-solving skills in Project Euler (https://projecteuler.net/) I noticed many persons using Haskell and this made me curious. I got into Haskell and now with this blog I am documenting that journey.My recent forage into Haskell has also been driven by my curiosity as to its usefulness as a teaching tool for Linear Algebra. As a functional language it should facilitate this so this is my quest. If you need additional motivation to learn Haskell, read this from eWeek.

I though once of writing a text but then cme across some great texts and that stumped me so I have decided just on recording these steps in the hope that they may be helpful to some other newbie like myself. As I go, I shall be updating this blog.  Learning a new language is fun and I recommend it! Let's go.

Reference Texts

These texts are really great. Take time to read them all...
You will be very happy!

Functional programming

Haskell is an advanced purely functional programming language. You can dabble a bit on the URL
https://www.haskell.org/ and while the code looks strange at first, we need to really get used to it to be able to make the most of it.

What is functional programming?

From this website http://www.functionalprogramming.com/, I have selected this definition:

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Functional programming has its roots in lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as elaborations on the lambda calculus.

Haskell Platform


In order to be able to use your computer to run Haskell code, you would have to download and install the Haskell platform: This can be done best from:https://www.haskell.org/downloads.

https://www.haskell.org

I have so far only experimented using Windows systems (Windows 7 and Windows 8). No doubt the processes are simple on Linux and OS based systems as well. This provides you with a development environment in which you can run code at the command prompt as well as load code from files in folders on your hard drive or wherever. There is a text editor in the IDE as well but I preferred to use Notepad++ (http://notepad-plus-plus.org/).

The system installed is the Glasgow Haskell Compiler (GHC) and the prompt is the Prelude> which you can change if you really want to but in my case I haven't done so. It does not take long to get used to the environment and within a few minutes you are up and running. I tend to use the WinCHCi and I have made a shortcut on my Windows 7 desktop so I can easily get into this system.

Introduction to Haskell

As a great first introduction to Haskell, I recommend "Learn You a Haskell for Great Good" which is available online at the URL  http://learnyouahaskell.com/. Read the text and practice the exercises so you get a good feel for the language and the environment as well. I did find that some of the interactive suggestions did not work but you always have to look for a go-around.

Once you have downloaded and installed the Haskell Integrated development Environment, you would be able to interact with it:

As you start to dabble in Haskell, it is best always to start with the interactive mode. Follow suggestions from the literature and try this and try that. I did some simple arithmetic and then went into some simple functions and just trying and trying and trying. This gives you a feel for what works even before you delve into the language definition itself.

Here are some suggestions:

Simple arithmetic using both infix and prefix notation:

Prelude> 5 + 4
Prelude> (+) 5 4
Prelude> 5/4

Expression Evaluation

Prelude>7 * 8 + 3

Assignments

We can assign a value to a variable x using the "let" statement

Prelude> let x = 4

and test that the variable x has been assigned the value as follows:

Prelude> x

Built-in Functions

Haskell has libraries of built-in functions such as exp which computes the exponent of an argument.

Prelude> exp 3 

This yields
 20.085536923187668

You can check that out using your favourite calculator!


Lists

We can create a list with two members 1 and 3 as follows:

Prelude>[1, 2]

and add a new member to the front of the list using the : operator

Prelude> 0 : [1, 2]
[0, 1, 2]


You can also use built-in functions such as length as follows:

Prelude> length [0, 1, 2]
3

We can even create lists of ordered pairs:

Prelude> [(n, 2 * n) |  n  <-  [1..5]]
[(1,2),(2,4),(3,6),(4,8),(5,10)]
Prelude>

That is, we want the list of ordered pairs for which the first element is n for n = 1 ..5 and the second is 2 * n.


Functions

We can construct some simple functions:

Prelude>let sq x = x * x

and test it using:

Prelude> sq 3

As you create more and more functions be careful not to use function names which already exist such as exp which is an in-built function.

Prelude>let myadd a b = a + b
Prelude>myadd 3 4

so that before embarking on writing "programs" one has a sense of what works and what does not work.

As you start creating simple sample programs, it is best to have them all stored in a folder. In my case, I created a folder called "Haskel" in my "Documents" and always store my code there.

Don't be too fast to run away from the interactive mode as for instance you can do something like the following:

Prelude> let isEven n = if mod n 2 == 0 then "yes!" else "no!"
Prelude>
isEven 5
"no!"


or even try printing the first five factorials


Function Composition

Given that Haskell is a functional programming language, you would expect that it supports function composition. It does!

Prelude> let f x = x * x
Prelude> let g x = 3 * x
Prelude> (f.g) 5
225
Prelude>  

Prelude> print [ (n, product [1..n]) | n <- [1..5]]
[(1,1),(2,2),(3,6),(4,24),(5,120)]


Can you make sense of the code in each of these instances?

So clearly the interactive mode is quite useful for helping us get into the language constructs and testing these before we actually use them in a program.

A program is a set of source code instructions which is saved in a file and loaded into the IDE and subsequently compiled and executed. In Haskell, program sub-components are divided into modules. We shall see more of that later. For the moment, we shall use only the Main module.

Hello, World!


Traditionally, the very first program one writes in a language is the "Hello, World" program:

 module Main
      where

main = putStrLn "Hello World"


This is important as it points to system functionality. The code is entered into the Notepad++ editor and saved in a folder called Haskell. In the Haskell IDE, the code is loaded and then executed.


Note that it is also possible to compile the code and produce an executable file which could be run directly from the operating system.

Flop Program


The Haskell equivalent to the swap procedure in most languages is the flop:

flop (a, b) = (b, a)
main = print $ flop (1, "one")


and finally in this set of illustrations we shall look at a simple program to compute the hypotenuse of a right-angled triangle using Pythagoras' Theorem which is quite well known among school children:

module Main where

hypt a b = sqrt(a * a + b * b)

main :: IO ()
main = print $ hypt 3 4


This last illustration gives us a format for simple programs with the module Main and then the main statement which defines the execution point of the program.

2 plus 2

Here is another fairly simple program:

-- | 2 plus 2

main = do putStrLn "What is 2 + 2?"
          x <- readLn
          if x == 4
              then putStrLn "You're right!"
              else putStrLn "You're wrong!"


Can you guess what it is doing?

Try it in your Haskell IDE.

Grocery List

Let's suppose we were asked to add up a set of prices in a grocery list. Maybe a set such as

23
45
67
89
12
11

How would you approach that?

nums = [
        23,
        45,
        67,
        89,
        12,
        11
        ]

main = print $ sum nums


Haskell Programming Tips


In this section, we shall look at some Haskell programming tips"

Indentation

In Haskell the indentation is important. Haskell uses a system called layout to automatically block its code so that statements within a block must have the same indentation.


Comments

Comments in Haskell start with --  as you can see from the "2 plus 2" program above. Comments are an important source of information within the code and would help to remind you of details of algorithms used and even persons responsible for different modules and parts of the source code. I tend to use comments at the beginning of the program to remind me of the file name, programmer and date of writing of the code as well.


Functions

You may have noted that all function names start with a common letter.Haskell requires that all function names and values start with common letters. The names given to types begin with a capital letter.


Modules


In Haskell, a program consists of a collection of modules. Modules help us divide up the code into manageable segments.  Module names are alphanumeric and must begin with a capital letter. We have been using the module Main.Modules must be imported for the functions to be used. As an example of the use of modules, consider the use of the module Data.List

Prelude> import Data.List
Prelude Data.List> sort [2, 1, 3]
[1,2,3]
Prelude Data.List> transpose [[1,2,3],[4,5,6],[7,8,9]]
[[1,4,7],[2,5,8],[3,6,9]]
Prelude Data.List> takeWhile (>3) [6,5,4,3,2,1,2,3,4,5,4,3,2,1]
[6,5,4]
Prelude Data.List> sort [8,5,3,2,1,6,4,2]
[1,2,2,3,4,5,6,8]
Prelude Data.List> group [1,1,1,1,2,2,2,2,3,3,2,2,2,5,6,7]
[[1,1,1,1],[2,2,2,2],[3,3],[2,2,2],[5],[6],[7]]
Prelude Data.List> partition (>3) [1,3,5,6,3,2,1,0,3,7] 
([5,6,7],[1,3,3,2,1,0,3])
Prelude Data.List> find (>4) [1,2,3,4,5,6] 
Just 5
Prelude Data.List> [1..7] `intersect` [5..10]
[5,6,7]
Prelude Data.List> insert 4 [3,5,1,2,8,2]
[3,4,5,1,2,8,2]
As we learn Haskell, we have to also familiarise ourselves with what is in the various modules. We can even write our own modules as well.

Input and Output

 Already in the program samples above you can see instances of both input and output. With the input statements we can enter arguments directly from the keyboard at run time while the output helps us see what the computed results are. The program "2 pls 2" has both input and output and is a good example.

Indentation

Readability of the code is another important facet of programming. It is necessary in Haskell and identifies the  various parts of the control segments of the program. Also, white spaces are important for both readability as well as the organisation of the code.

No hay comentarios.:

Publicar un comentario