Type in some simple expressions at the Hope prompt >: like:
1; 1+1; 'a'; true and false;
factorial: num -> num; factorial(0) <= 1; factorial(n+1) <= (n+1)*factorial(n);
Use is to work out factorial of five, ten and twenty.
fib: num -> num; fib(n) <= if (n<2) then 1 else fib(n-1) + fib(n-2);solution
mult: num # num -> num; mult(0,m) <= 0; mult(n+1,m) <= m+ mult(n,m);Define mult in Java. solution
gcd: num # num -> num; gcd(n,m) <= if (n=m) then n else if n>m then gcd(n-m,m) else gcd(m,m-n);Program this in Java.
import java.util.*; public class genericLists <T> { public T head (ArrayList <T> m) { return m.get(0); } public ArrayList <T> tail (ArrayList <T> t) { ArrayList <T> m= new ArrayList <T> (t); m.remove(0); return m; } public ArrayList <T> nil () { return new ArrayList <T>(); } public ArrayList <T> cons (T t, ArrayList <T> m) { ArrayList <T> k= new ArrayList <T>(); k.add(t); k.addAll(m); return k; } public ArrayList <T> append (ArrayList <T> t, ArrayList <T> u) { if (t.isEmpty()) return u; else return cons(head(t),append(tail(t),u)); } public ArrayList <T> reverse (ArrayList <T> t) { if (t.isEmpty()) return t; else return append(reverse(tail(t)),cons(head(t),new ArrayList <T>())); } }
Watch video (Write recursive methods using the basic Generic List Methods))
makebetween: num # num -> list(num); makebetween (n,m) <= if (n=m) then [n] else n::makebetween(n+1,m);Program this in Java. solution
reverse: list(alpha) -> list(alpha); reverse(nil) <= nil; reverse(x::l) <= reverse(l) <> [x]; revrev: list(list(alpha)) -> list(list(alpha)); revrev(nil) <= nil; revrev(x::l) <= revrev(l) <> [reverse(x)];
try: e.g.
revrev[[1,2.3],[4,5,6]];
Program revrev in Java. solution
To Sort a list of integers into descending order, if it's empty return the empty list otherwise sort the tail and inser the head in the right place.
Here is the solution in Hope:
insert: num # list(num) -> list(num); insert(x,nil) <= [x]; insert (x,y::m) <= if (x<y) then y::insert(x,m) else x::(y::m); sort: list(num) -> list(num); sort(nil) <= nil; sort(x::m) <= insert(x,sort(m));
Try it out!
Complete this Java program to sort a list into ascending order:
import java.util.*; public class sort { static genericLists <Integer> L = new genericLists <Integer>(); static ArrayList <Integer> insertAscending (Integer x, ArrayList <Integer> l) { } static ArrayList <Integer> sortAscending (ArrayList <Integer> l) { } public static void main(String [] args) { System.out.println((maker.makeR(Integer.parseInt(args[0])))); //use your makeR method from before. System.out.println(sortAscending(maker.makeR(Integer.parseInt(args[0])))); } }solution
s.danicic@gold.ac.uk