JDBC 3: Queries

Fetch ResultSet

Once you have a connection, you can now fetch data from the database. Add the following method to the DBase class.

  • The method creates a statement attached to the connection con.
  • The statement executes a simple MySQL query. The query results are stored in a ResultSet rs.
  • A pointer is set to before the first record in the ResultSet.
  • A while statement is used to traverse the set.
  • Finally, the connection is closed.
public static void printPupils() {

    Statement statement;
    makeConnection();
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM Student");

        while (rs.next()) {
        System.out.println("Forename: " + rs.getString("Forename") 
                  + " Surname: " + rs.getString("Surname")
                  + " Gender: " + rs.getString("Gender") 
                  + " Form: " + rs.getString("Form"));
        }

        con.close();

    } catch (SQLException ex) {
        System.err.println(ex);
    }
}
package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

    DBase.printPupils();
    }

}

Add a record using a PreparedStatement

Note that we use executeQuery() to retrieve data and executeUpdate() to update the database.  Here we’ve hard coded the student we’re adding.   A later section will show how to add any student.

public static void addStudent() {

       makeConnection();
       try {
       PreparedStatement prep 
           = con.prepareStatement("INSERT INTO Student
        (Forename, Surname, Gender, Form) 
           VALUES (?,?,?,?)");
       prep.setString(1, "Last");
       prep.setString(2, "James");
       prep.setString(3, "M");
       prep.setString(4, "9C");

       prep.executeUpdate();

       con.close();

       } catch (SQLException ex) {
       System.err.println(ex);
       }

   }
package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    DBase.addStudent();
    DBase.printPupils();
    }

}

JDBC 2: Database Class

The following is the class I’m going to use for the main part of this tutorial. It’s just the Quick Start code broken down into methods.

package dbase2016;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author ajb
 */
public class DBase {

    private static Connection con;

    DBase() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            System.err.println(ex);
        }

    }

    public static void makeConnection() {
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", "");
        } catch (SQLException ex) {
            System.err.println(ex);
        }

    }


    }

}

Check the connection by calling the makeConnection() method as follows. If everything is okay the program will simply terminate. If an exception is thrown, check your port number, username and password.

package dbase2016;

/**
 *
 * @author ajb
 */
public class DBase2016 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    DBase.makeConnection();
    }

}

– More Collections: Return to Lisp Problems Solutions

1 Last Item

Find the last item in an List of String objects

1.1 Solution

1: String lastItem(List<String> a)
2: {
3:     return  a.get(a.size()-1);
4: }

2 Last Item Generic

Find the last item in a Generic List

2.1 Solution

1: Object gLastItem(List<?> a)
2: {
3:     return  a.get(a.size()-1);
4: }

3 Last But One

Find the last but one item in a List

3.1 Solution

1: Object lastButOneItem(List<?> a)
2: {
3:     if (a.size() > 1) 
4:  return  a.get(a.size()-2);
5:     else  
6:  return "List too small";
7: }

4 Iterate through the Elements of a List

Iterate through the Elements of a List, printing them out in turn

4.1 Solution

1: void printEach(List<?> a)
2: {
3:     for (Object e: a)
4:     {
5:  System.out.println(e);
6:     }        
7: }

or using a stream

1: void streamPrintEach(List<?> list)
2: {
3:     list
4:  .stream()
5:  .forEach(System.out::println);
6: 
7: }

5 Eliminate consecutive duplicates from a List.

Write a method that removes consecutive duplicates from a List. The order of the elements should not be changed.

5.1 Solution

1: List<?> removeDuplicates(List<?> a)
2: {
3:     for (int i = 0; i<a.size()-1; i++)
4:     {
5:  if(a.get(i) == a.get(i+1)) a.remove(a.get(i));        
6:     }
7:     return a;
8: }

6 Eliminate consecutive duplicates from a List using HashSet

Remembering that a HashSet cannot contain duplicates, repeat the above question using a HashSet

6.1 Solution

1: HashSet<String> hashRemoveDuplicates(List<String> a)
2: {
3:     HashSet<String> hSet = new HashSet<String>(a);
4:     return hSet;
5: }

7 RLE

Run-length encoding of a list. Consecutive duplicates of elements are encoded as pairs where N is the number of duplicates of the element E.

Note this solution uses the Pair class, defined in the question

7.1 Solution

 1: List<Pair> RLE(List<?> list)
 2: {
 3:     List<Pair> encoded = new ArrayList<Pair>();
 4:     for (int i = 0; i < list.size(); i++)
 5:     {
 6:     int runLength = 1;
 7:     while (i < list.size() -1 && list.get(i) == list.get(i+1))
 8:     {
 9:         runLength++;
10:         i++;
11:     }
12: 
13:      Pair<Object> pair = new Pair<Object>(runLength, list.get(i));
14:      encoded.add(pair);
15:     }
16:     return encoded;
17: 
18: }

8 Decode a run-length encoded list

Given a run-length code list generated in a previous problem, construct its uncompressed version.

Note this solution uses the Pair class, defined in the question

8.1 Solution

 1: List<Object> decodeRLE(List<Pair> list)
 2: {
 3: 
 4:     List<Object> decoded = new ArrayList<Object>();
 5:     for (Pair pair: list)
 6:     {
 7:     for (int i =0; i<(int)pair.count; i++)
 8:     {
 9:         decoded.add(pair.value);
10:     }
11:     }
12: 
13:     return decoded;
14: }

9 Duplicate the elements of a list

9.1 Solution

 1: List<String> dupli(List<String> list)
 2: {
 3:     List<String> dup = new ArrayList<String>();
 4: 
 5:     for(String s: list)
 6:     {
 7:     dup.add(s);
 8:     dup.add(s);
 9:     }
10: 
11:     return dup;
12: }

or, using a stream

1: List<String> streamDupli(List<String> list)
2: {
3:     List<String> dupli = list
4:              .stream()
5:              .collect(Collectors.toList());
6: 
7:     return dupli;        
8: 
9: }

10 Replicate the elements of a list a given number of times

10.1 Solution

 1: List<String> repli(List<String> list, int num)
 2: {
 3:     List<String> rep = new ArrayList<String>();
 4: 
 5:     for(String s: list)
 6:     {
 7:     for (int i=0; i<num; i++)
 8:     {
 9:         rep.add(s);
10:     }
11:     }
12: 
13:     return rep;
14: }

7: More Collections: Return to Lisp Problems

These problems were inspired by the 99 Lisp problems. Lisp is a very different language to Java; its use of lists means it’s not appropriate to emulate all the original problems in Java, however, there is some benefit in practising the use of Java collections.

The introduction of lambda functions in Java8 made me rethink how best to approach these problems. There are three things being practised here: collections, generics and lambdas. I’ve split up the questions so that they give a chance to practice these different skills.

1 Last Item

Find the last item in an List of String objects

1.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastItem(myList));
3:  *** Output ***
4: spoon

2 Last Item Generic

Find the last item in a Generic List

2.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: List<Integer> anotherList = new ArrayList<>(asList(1,2,3));
3: System.out.println(gLastItem(myList));
4: System.out.println(gLastItem(anotherList));
5:  *** Output ***
6: spoon
7: 3

3 Last But One

Find the last but one item in a List

3.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastButOneItem(myList));
3:  *** Output ***
4: fork

4 Iterate through the Elements of a List

Iterate through the Elements of a List, printing them out in turn

4.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(printEach(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

5 Eliminate consecutive duplicates from a List

Write a method that removes consecutive duplicates from a List. The order of the elements should not be changed.

5.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

6 Eliminate consecutive duplicates from a List using HashSet

Remembering that a HashSet cannot contain duplicates, repeat the above question using a HashSet

6.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

Remembering that a HashSet cannot contain duplicates

7 RLE

Run-length encoding of a list. Consecutive duplicates of elements are encoded as pairs where N is the number of duplicates of the element E.

Use this Pair class

 1: class Pair<T>
 2:    {
 3:        int count;
 4:        T value;
 5: 
 6:        Pair(int count, T value) 
 7:        {
 8:        this.count = count;
 9:        this.value = value;
10:        }
11: 
12:        void print()
13:        {
14:        System.out.print("("+ count + ", " + value +") ");
15:        }
16:    } 

7.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2:  List<Pair> rle = RLE(myList);
3:  for (Pair r: rle)
4:  {
5:      r.print();
6:  }
7:  System.out.println("");
8:  *** Output ***
9: (2, knife) (1, fork) (2, spoon)

8 Decode a run-length encoded list

Given a run-length code list generated in a previous problem, construct its uncompressed version.

8.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2:     List<Pair> rle = RLE(myList);
 3:     for (Pair r: rle)
 4:     {
 5:         r.print();
 6:     }
 7:     System.out.println("");
 8: 
 9:     List<Object> decoded = decodeRLE(rle);
10: 
11:     for (Object o: decoded)
12:     {
13:         System.out.println(o);
14:     }
15:  *** Output ***
16: (2, knife) (1, fork) (2, spoon) 
17: knife
18: knife
19: fork
20: spoon
21: spoon

9 Duplicate the elements of a list

9.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(dupli(myList));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: fork
 9: fork
10: spoon
11: spoon
12: spoon
13: spoon

10 Replicate the elements of a list a given number of times

10.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(repli(myList,3));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: knife
 9: knife
10: fork
11: fork
12: fork
13: spoon
14: spoon
15: spoon
16: spoon
17: spoon
18: spoon

Welcome

This blog’s tagline is adapted from the Emacs Org-Mode motto. It seemed appropriate, as I seem to have spent most of my life writing novels and short stories (of which you can find out more at tonyballantyne.com) or teaching computer coding.

I’ve amassed a lot of material over the years, and I wanted to share it with people who may not have had the same access to education as people living in my country are lucky enough to have. If you want to change the world, become a teacher.

As the the teaching of coding seems to be coming back into fashion, I’ve also included my thoughts on the pedagogy of this subject.

All comments are gratefully received.

JDBC 1: Set up

Create a Database to query

First, set up a MySQL database. For the purposes of this demonstration I set up a simple database called bluecoat with one table: student. The table has four columns of type varchar: Forename, Surname, Gender and Form.

Add mysql-connector JAR

You will need to download the mysql-connector JAR and add it to your classpath. Consult your IDE’s documentation on how to do this.

You can find the JAR here: https://dev.mysql.com/downloads/connector/j/

If you’re using Netbeans, right click on the Libraries folder and choose Add JAR/Folder

The JAR is installed by default in the ext folder on windows:

 

Quick Start

The following code will connect to a database called bluecoat running on a mysql server on port 3306 of localhost. I used XAMPP to write this tutorial: by default the username of the database was root, the password was left blank.

try {
//Load mysql jdbc Driver      
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Connect to Database      
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bluecoat", "root", "");
} catch (Exception ex) {
      System.err.println(ex);
}

Run the code. If it doesn’t throw an exception, you’re successfully connected!

MyKitaab Podcast

The mission of the MyKitaab podcast series is to help answer the question “I have written a book, how do I get it published in India?”
Here, host Amar Vyas talks to me about writing, blogging and Open Source software, especially  Emacs!
You can access the podcast as follows:

Or listen to it here:

Functional Programming in Haskell for A level teachers

About this document

Functional Programming is now part of the A level curriculum. This document is intended to get those who already have some programming experience in an imperative language (such as Python or Java) up and running in Haskell, one of the functional languages recommended by AQA specification 7516.

Important!

Please note, if you have no experience of programming, then this document is not for you. Try learning an imperative language such as Python first.
This is far from being a full course in Haskell, it’s purely intended to get you through the A level syllabus. Many important features of Haskell are omitted, the most important being how Haskell handles types – you’ll need to learn about these if you want to learn Haskell properly.
A good place to start is http://learnyouahaskell.com/ by Miran Lipovaca

Getting Started

Installation

Before you start, you’ll need to install the Haskell Platform. This contains, amongst other things, the Haskell compiler GHC and the Haskell interpreter GHCi. If you install the Windows version you’ll also get WinGHCi, a simple GUI for the interpreter.
https://www.haskell.org/platform/index.html

Using the Haskell Interpreter

Once everything’s installed, open the Haskell interpreter by either running ghci in a terminal or opening WinGHCi in Windows.
The Haskell interpreter will load, showing the Prelude> prompt. Prelude refers to the standard module imported by default into all Haskell modules: it contains all the basic functions and types you need.
Try out some arithmetic operators as follows:

Prelude> 3+4
7
Prelude> (5*6)+7
37
Prelude> 2^12
4096

Saving Your Work

Haskell programs aren’t intended to be written as line after line of code, but rather as a collection of functions. Haskell programs are a little like a spreadsheet: you write lots of functions that call each other.
Here’s an example of how to save your functions and load them into the interpreter.

  1. Open your favourite text editor (Notepad, Notepad++, TextEdit, Emacs, Vim, …) and type in some Haskell functions. I’ve given two simple examples below.
areaCircle x = 3.14 * x
areaSquare x = x * x
  1. Save the file. I’ve saved my file as c:/haskell/example.hs
  2. Run the Haskell interpreter
  3. Type :l c:/haskell/example.hs to load your functions into the interpreter. You should see that the prompt now says Main>. Main refers to the module you just loaded. Note, you still have access to the Prelude functions
  4. Experiment using your functions in the Haskell interpreter. If you make changes to your functions, hit :r to reload the file.
areaCircle 3
9.42
areaSquare 4
16

Exercise

Write a functions to work out the following

  1. The perimeter of circle
  2. The perimeter of a square
  3. The perimeter of a rectangle

Lists

AQA Quick Reference

The following is taken from the AQA syllabus:
Be familiar with representing a list as a concatenation of a head and a tail. Know that the head is an element of a list and the tail is a list.
Know that a list can be empty.
Describe and apply the following operations:

  • return head of list
  • return tail of list
  • test for empty list
  • return length of list
  • construct an empty list
  • prepend an item to a list
  • append an item to a list.

Have experience writing programs for the list operations mentioned above in a functional programming language or in a language with support for the functional paradigm

Syllabus Haskell Example
Create a list let xs = [1,2,3,4,5]
return head of list head xs
return tail of list tail xs
test for empty list null xs
return length of list length xs
construct an empty list xs = []
prepend an item to a list element : xs
append an item to a list xs ++ [element]

Going beyond the specification, there are many more list examples here: https://wiki.haskell.org/How_to_work_on_lists

Using Lists

Haskell lists are homgenous: all the elements must be the same type.

  • [1,2,3] OK
  • [‘a’,’b’,’c’] OK
  • [1,’b’,2] X Not allowed

A string is simply a list of characters
“This” = [‘T’,’h’,’i’,’s’]
Haskell lists have a head and tail, they also have an init and a last (see below for examples of these). You can prepend an element to a list (add it to the front) using the : operator, and concatenate (join) two lists using the ++ operator.
Use the : operator for preference in Haskell: it’s much faster than ++
Here are some examples to illustrate the above

Prelude> let xs = [1,2,3,4,5]
Prelude> head xs
1
Prelude> tail xs
[2,3,4,5]
Prelude> init xs
[1,2,3,4]
Prelude> last xs
5
Prelude> tail xs ++ init xs
[2,3,4,5,1,2,3,4]
Prelude> head xs ++ last xs
<interactive>:15:1:
    No instance for (Num [a0]) arising from a use of ¡®it¡¯
    In a stmt of an interactive GHCi command: print it
Prelude> [head xs] ++ [last xs]
[1,5]
Prelude> xs!!2
3
Prelude> xs!!6
 *** Exception: Prelude.(!!): index too large
Prelude> xs!!0
1
Prelude> 0:xs
[0,1,2,3,4,5]
Prelude> xs ++ 6
<interactive>:25:1:
    No instance for (Num [a0]) arising from a use of ¡®it¡¯
    In a stmt of an interactive GHCi command: print it
Prelude> xs ++ [6]
[1,2,3,4,5,6]

List Exercise

  1. Write a list containing the days of the week
  2. Find the head of the list
  3. Find the tail of the list
  4. Find the last element of the list
  5. Find the last but one element of the list
  6. A new day is invented: Haskellday. Prepend this to the list

Remember that a string is a list of characters. Let name = <your name>

  1. Find the first character in your name
  2. Find the last character
  3. Find the length of your name.
  4. Find all the characters but the last.
  5. What output will the following produce?
let ls = [1,2,3,4,5]
last ls:init ls ++ tail ls ++ [head ls] ++ [ls!!3]
  • Why is [head ls] written as a list, and not as an element, eg head ls?

A Brief Diversion: List Comprehensions and Ranges

List Comprehensions aren’t mentioned on the AQA syllabus, but they’re too powerful a feature not to take a look at. It’s worth understanding how they work: similar functionality has been introduced into languages such as Java.
Let’s start with some ranges

Prelude> [1..5]
[1,2,3,4,5]
Prelude> [1,3..10]
[1,3,5,7,9]
Prelude> [10,9..1]
[10,9,8,7,6,5,4,3,2,1]
Prelude> [-5,-3..5]
[-5,-3,-1,1,3,5]

Now for some list comprehensions. The following examples show how to draw down from ranges in a list comprehension

Prelude> [x*2 | x <- [1..5]]
[2,4,6,8,10]
Prelude> [x*x | x <- [1..10]]
[1,4,9,16,25,36,49,64,81,100]

You can add predicates to restrict the values of a list comprehension as follows

Prelude> [x | x <- [1..10], odd x]
[1,3,5,7,9]

You can add more than one predicate. What are the even numbers between 1 and 50 that are divisible by 3?

Prelude> [x|x<-[1..50], x `mod` 3==0, even x]
[6,12,18,24,30,36,42,48]

You can draw down from two variables as follows. Watch out for the order! Note that x**y means x to the power of y

Prelude> [x**y | x <- [1..5], y <- [2,3,4]]
[1.0,1.0,1.0,4.0,8.0,16.0,9.0,27.0,81.0,16.0,64.0,256.0,25.0,125.0,625.0]
Prelude> [x**y | y <- [2,3,4], x <- [1..5]]
[1.0,4.0,9.0,16.0,25.0,1.0,8.0,27.0,64.0,125.0,1.0,16.0,81.0,256.0,625.0]

List Comprehension Exercise

Use list comprehensions to produce the following lists:

  1. [5,10,15,20,25,30,35,40,45,50,55,60]
  2. [0.5,0.4,0.3,0.2,0.1,0]
  3. [3,2,1,0,-1,-2,-3]
  4. [1,8,27,64,125,216,343,512,729,1000]
  5. [1,3,5,7,9]
  6. [100,102,104,106,108,110,112,114,116,118,120]

Haskell and Lazy Evaluation

Haskell doesn’t work things out until it has to – this is called lazy evaluation.
This means you can write down things that might not lead to errors in imperative languages.
For example

take 5 [1..]
[1,2,3,4,5]

The above means take the first 5 elements from the infinite list that counts up from 1. Haskell only creates as much of the list as it needs.
Combining lazy evaluation with functions that produce infinite lists means you can do such things as the following

Prelude> take 10 (cycle [1,2])
[1,2,1,2,1,2,1,2,1,2]
Prelude> take 5 (repeat "Brubeck")
["Brubeck","Brubeck","Brubeck","Brubeck","Brubeck"]

Summary

  • Haskell allows you to use list comprehensions to work out lists of numbers.
  • A list comprehension draws down from a range (e.g. x <- [1..10]) or a number of ranges.
  • You can apply predicates (e.g. odd or even) to your list comprehension to decide what goes in it.
  • List comprehensions allow you to solve problems in a completely different way to imperative programming languages. For example, here’s how you’d find all the pythagorean triples (numbers such that a2 = b2+c2) for a,b,c <x.
pythagTriples x = [(a, b, c)  | a <-[1..x], b <- [1..x], c <- [1..x], c^2 == a^2 + b^2]

More on Functions

More than one parameter

Here are the two Haskell functions used in the Getting Started section:

areaCircle x = 3.14 * x
areaSquare x = x * x

Note that Haskell functions must start with lower case letters.
Remember, whilst you are learning you can type up functions in your favourite editor and then load them into the editor using :l path/to/file. Use :r to reload the functions when you’ve made changes to them.
Here’s how to write functions with two parameters:

areaRectangle l w = l*w
perimeterRectangle l w = 2*l + 2*w

Partial Application

AQA defines partial application as the process of applying a function by creating an intermediate function by fixing some of the arguments to the function
As and example, lets consider the areaRectangle function above. Suppose you want to work out the areas of all rectangles where one side is fixed at 3. You can write a function, area3Rect, as follows

area3Rect = areaRectangle 3

You can now work out the areas of different rectangles as follows

*Main> area3Rect 4
12
*Main> area3Rect 5
15
*Main> area3Rect 6
18
*Main>

area3Rect is a partially applied function – a function where some of the parameters have been fixed.
Try creating a partially applied function based on perimeterRectangle.
This leads us nicely on to Higher Order Functions…

Higher Order Functions

AQA Quick Reference

A function is higher-order if it takes a function as an argument or returns a function as a result, or does both.
Have experience of using the following in a functional programming language:

  • map
  • filter
  • reduce or fold.

map is the name of a higher-order function that applies a given function to each element of a list, returning a list of results.
filter is the name of a higher-order function that processes a data structure, typically a list, in some order to produce a new data structure containing exactly those elements of the original data structure that match a given condition.
reduce or fold is the name of a higher-order function which reduces a list of values to a single value by repeatedly applying a combining function to the list values.

Syllabus Example
map map (+3) [1,2,3,4,5] -> [4,5,6,7,8]
filter filter (>3) [1,2,3,4,5] -> [4,5]
fold foldl (+) 0 [1..10] -> 55

Map

The Map function applies a function to every element of a list. In other words, it’s a function that takes a function as a parameter, in other words a higher order function.
Here we map the function (+3) to the list

*Main> map (+3) [1,2,3,4,5]
[4,5,6,7,8]

Here we map the odd function…

*Main> map odd [1..10]
[True,False,True,False,True,False,True,False,True,False]

Filter

The filter function filters a list according to a predicate – a function that returns true or false. Filter is therefore a higher order function, a function that takes a (predicate) function as a parameter.
Here we filter the numbers >3 from the list.

*Main> filter (>3) [1,2,3,4,5]
[4,5]

Here we filter out the odd numbers in a list.

*Main> filter (odd) [1..20]
[1,3,5,7,9,11,13,15,17,19]

A string in Haskell is treated as a list of letters. `elem` returns true if the letter is an element of the list so…

*Main> filter (`elem` ['A'..'Z']) "What Are The Capitals In This Sentence?"
"WATCITS"

Fold

A fold has three parts. A function, and accumulator and a list to work on.
Haskell gives you two types of fold, foldl which folds from the left side of a list, and foldr which folds from the right.
Fold works it way through a list one item at a time, performing an operation on that item and storing it in the accumulator.
This is probably best demonstrated with a few examples

Prelude> foldl (+) 0 [1..10]
55
Prelude> foldr (+) 0 [1..10]
55
Prelude> foldl (-) 0 [1..10]
-55
Prelude> foldr (-) 0 [1..10]
-5

The first example is quite straighforward. Foldl takes the first item from the list (1) adds it to the accumulator (0) and stores the result in the accumulator (1)
It then takes the second item from the list (2) adds it to the accumulator and stores the result (3). Working through the list you get the result 55.
The second and third examples are similar.
The last example is particularly interesting, however. Why does it give the result -5? Try and work through the logic, and remember that if you subtract a -ve number its the same as adding
You can use fold in haskell like you use loops in imperative languages

Exercises

  1. Use the map function on a list [1..5] to produce a list [2..6]
  2. Use the map function on a list [1..10] to produce a list of even numbers [2..20]
  3. Use the filter function to find the odd numbers between 1 and 30
  4. Use the filter function to find the numbers <4 in the list [1..10]
  5. Use the foldl function to add up the numbers from 1 to 100
  6. Use the foldr function to find 4! (4 x 3 x 2 x 1)

Beyond the AQA specification

The following are not part of the current specification. I’ve included in case you want to get more of a taste of Haskell…

Pattern Matching

Haskell allows pattern matching. The following function counts one, two or many objects

simpleCount 1 = "One"
simpleCount 2 = "Two"
simpleCount x = "Many"

You can use pattern matching to set base cases in recursive functions. Here’s an example of a factorial function from later on. Note how factorial 0 is defined as being 1 using pattern matching.

factorial 0 = 1
factorial n = n * factorial (n-1)

ifs and guards

Haskell allows you to use ifs and guards in your functions. A guard is a more readable version of an if.
People can learn to drive from the age of 17 in the UK. The following function uses to an if statement to check if someone is old enough to drive

canDrive x = if x <18 then  "Too young to drive" else "Old enough to drive"

Here it is using guards:

canDrive' x
          | x<18 = "Too young to drive"       |
          | otherwise = "Old enough to drive" |

The following function uses guards to work out the cost in pence of sending a large letter in the UK

letterCost weight
       | weight <= 100 = 96
       | weight <= 250 = 127
       | weight <= 500 = 171
       | otherwise = 2.46

Looking at the above letterCost function you might reasonably deduce that you could send an elephant via the UK postal service for £2.46. Unfortunately, the prices given are only for large letters which can weigh no more than 1kg.

show

What if you want to mix text and numbers when using ifs and guards?
For example, in the game of fizz, you say “Fizz” if a number is divisible by 3, otherwise you just say the number. Writing a funciton to implement this can cause a problem in Haskell, as the function will have to return text or a number. One way round this is to convert the number to text using show, as follows.

fizz n
  | n `mod` 3 == 0  = "Fizz"
  | otherwise = show n

Pattern Matching, Ifs and Guards Exercise

Write the following functions:

  1. A function that returns “Zero” if 0 is passed, then “Odd Number” or “Even Number” if an odd or even number is passed.
  2. A grade function that calculates students grade as follows: A >50, B >40, C>30 otherwise fail
  3. A fizz function, the returns “Fizz” if a number is divisible by three, otherwise it just returns the number
  4. A buzz function, the returns “Buzz” if a number is divisible by five, otherwise it just returns the number
  5. A FizzBuzz Function that returns “FizzBuzz” if a number is divisible by 3 and 5, Fizz if it’s divisible by three and Buzz if it’s divisible by five. Otherwise, just return the number.

Functions and List Comprehensions

Let’s define a function that uses a list comprehension to find the factors of n

factors n = [x | x <- [1..n], n `mod` x == 0]

Now, remembering that a number n is prime if and only if it has two factors, [1,n], let’s define function to determine if a number is prime

prime n = factors n == [1,n]
*Main> factors 15
[1,3,5,15]
*Main> factors 7
[1,7]
*Main> prime 7
True
*Main> prime 2
True

Oops, 2 is not a prime number. Use pattern matching to fix the prime function…

prime 2 = False
prime n = factors n == [1,n]

Check that…

*Main> prime 7
True
*Main> prime 2
False

Done!

Recursive Functions

Pattern matching is very useful when writing recursive functions. Recursive functions work very well on Haskell: it was designed for them. Here’s an example of a recursive function in Haskell

factorial 0 = 1
factorial n = n * factorial (n-1)

As you can see, pattern matching makes it very easy to set the base case for a recursive function. Here’s another recursive function. This one reverses a list. I’ve called my function reverse’ to distinguish it from the existing Haskell reverse function,

reverse' [] = []
reverse' (x:xs) = reverse(xs)++[x]

There are two important things to note here:
First, pattern matching is used to ensure the case of an empty list is handled.
Second, note the use of the (x:xs) pattern to identify the head and the tail of the list. Haskell programmers use this pattern a lot.

Recursion Exercise

Here some recursion problems from the Daily Java. See if you can solve them using Haskell

  1. The first 6 triangle numbers are 0, 1, 3, 6, 10, 15. The nth triangle number is 1 + 2 + 3 + … + n. Write a recursive method to find the nth triangle number
  2. Write a recursive method that returns m to the nth power, e.g. 2 to the power of 3 returns 8.
  3. The Harmonic Series begins 1 + 1/2 + 1/3 + 1/4 + 1/5 + … Write a recursive method that finds the Harmonic Series up to the nth term.
  4. The Fibonacci Series begins 1,1,2,3,5,8,13,… The next digit is the sum of the last two digits, so 1 + 1 = 2, 1 + 2 = 3 etc. Write a recursive method to print the nth fibonacci number

Lambda Functions

Lambda functions are sometimes called anonymous functions. Quite simply, they are a function without a name. It’s often more convenient to not bother naming a function when you’re only going to use it once.
Lambda is a Greek letter that looks like this: λ
Haskell uses a \ as it looks a little like a lambda.
Here’s an example of a lambda function that doubles a number

*Main> (\x -> x*2) 3
6

Here’s another lambda function that multiplies two numbers

*Main> (\x y -> x*y) 3 4
12

The above example is an anonymous version of the areaRectangle function mentioned earlier.
Here’s how to use a lambda function to find the numbers that divide by 3

*Main> filter (\x -> x `mod` 3 == 0) [1..20]
[3,6,9,12,15,18]

Putting it all together: Perfect Numbers

Here’s a Haskelly way of solving a problem, using some of the things learned so far.
A perfect number is a number that is the sum of its factors. 6 is a perfect number as its factors are 1, 2 and 3 and 1 + 2 + 3 = 6.
Find all the perfect numbers < 10000
We know from earlier that we can find the factors of a number using the following function

factors n = [x | x <- [1..n], n `mod` x == 0]

Here’s an example

*Main> factors 6
[1,2,3,6]

Remember that a number is perfect if it’s the sum of its factors, not including the number itself, so we add an extra predicate to eliminate that.

factors n = [x | x <- [1..n], n `mod` x == 0, x/=n]

Check this

*Main> factors 6
[1,2,3]

So a number is perfect if sum (factors x) == x. Lets run a list comprehension to find the perfect numbers <1000.

*Main> [x | x <- [1..1000], sum (factors x) == x]
[6,28,496]

Or use a filter…

*Main> filter (\x -> sum(factors x) == x) [1..1000]
[6,28,496]

Try running that on [1..10000] to see how long it takes Haskell to figure out the next perfect number!

8 – Strings and Characters

Sample Code

 String, char, int

public class StrAsc
{
    public static void main (String args [])
    {
        String s = "A String";
        System.out.println("The character at index 2 is " + s.charAt(2));
        System.out.println("The ASCII equivalent is " + (int)s.charAt(2));
    }
}

Exercises

  1. Convert the following string to its ASCII values: “I never saw a purple cow”
  2. If a = 1, b=2, c=3… convert the following String to its equivalent character codes: “DailyJava”
  3. ROT13 (“rotate by 13 places”, sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher, developed in ancient Rome. Write a program that will accept a String as input then output that string under a ROT13 transformation, so input of HELLO will result in output of URYYB
  4. Write a ROT-N cipher, similar to a ROT13 cipher, where a string and a shift are input, and a string is outputted with the characters shifted by N, so if the input is “DAD” and 1, the output is “EBE”
  5. Write a program that uses ASCII values to convert lowercase characters to uppercase, so input of “this” will result in output of “THIS”. DO NOT use library methods such as toUpperCase()
  6. There are 62 Alphanumeric Characters: [A-Za-z0-9]. Any other character, such as %,(): is non-alphanumeric. There are also a number of control or non-printing characters. These include Line Feed, Carriage Return and Tab. Write a program that imports a text file and prints the number of alphanumeric characters it contains.
  7. Write a program that accepts a string cipher as an input and ouputs a string plaintext containing every second letter from input. Test your program using the input “Knives” and “Forks”. You should get the output “nvs” and “ok” respectively

7 – Methods Answers

1) Write a method that accepts the length and width of a rectangle and returns the perimeter of the rectangle

double Perimeter(double length, double width)
{
    return length*2 + width*2;
}

2) Write a method that accepts the base and height of a triangle and returns the area of the triangle

double areaTriangle(double base, double height)
{
   return 0.5*base*height;
}

3) Write a method that accepts three integers as paramaters and returns the average of the integers.

double average(int a, int b, int c)
{
    return((a+b+c)/3.0);
}

4) Write a method that accepts an integer array as a parameter and returns the average of the values of that array.

double average(int [] numbers)
{
    double av = 0;
    double total = 0;
    for(int n: numbers)
    {
    total += n;
    }
    return total/numbers.length;
}

5) Write a method that accepts an integer array as a parameter and returns the minium value in that array

double min(int [] numbers)
{
    int minVal = numbers[0];
    for (int n : numbers)
    {
    if (n < minVal) minVal = n;
    }
    return minVal;
}

or

double min(int [] numbers)
{
    Arrays.sort(numbers);
    return numbers[0];
}

6) Write a method that returns the hypotenuse of a triangle when the other two sides are int a and int b. (Remember: hypotenuse squared equals a squared plus b squared)

double hypotenuse(double a, double b)
{
    return Math.sqrt(a*a + b*b);
}

7) The scalar product of u=(u1,u2,u3) and v=(v1,v2,v3) is defined to be u1v1+u2v2+u3v3. Write a method that accepts two int arrays as parameters and returns an int representing the scalar product of those two arrays

double scalarProduct(int [] u, int [] v) throws Exception
{
    if (u.length != v.length) throw new Exception();
    double product = 0;
    for(int i = 0; i<u.length; i++)
    {
    product += u[i]*v[i];
    }
    return product;
}

8) If A = (a1,a2, …an) and B = (b1,b2, …bn) then the vector sum of the two arrays A + B = (a1+b1, a2+b2, … , an+bn). Write a method that accepts two arrays as parameters and returns an array representing the vector sum of those two arrays.

double [] vectorSum(int [] u, int [] v) throws Exception
{
    if (u.length != v.length) throw new Exception();
    double [] sum = new double[u.length];
    for(int i = 0; i<u.length; i++)
    {
    sum[i] = u[i] + v[i];
    }
    return sum;
}

9) The Euclidean distance between two points A = (a1,a2, …an) and B = (b1,b2, …bn) is defined as sqrt((a1-b1)2 + (a2-b2)2 +… + (an-bn)2). Write a method that accepts two int arrays representing A and B as parameters and returns a double representing the Euclidean distance between them.

double [] eDistance(int [] u, int [] v) throws Exception
{
  if (u.length != v.length) throw new Exception();
  double [] sum = new double[u.length];
  double dist = 0;
  for(int i = 0; i<u.length; i++)
  {
       dist += Math.pow((u[i]-v[i]),2);
  }
  return sum;
}