Advertisement
Guest User

Untitled

a guest
Feb 4th, 2017
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. begin # Algol-68 prime number sieve, functional style #
  2.  
  3.   proc error = (string s) void:
  4.      (print(( newline, " error: ", s, newline)); goto stop);
  5.   proc one to = (int n) list:
  6.      (proc f = (int m,n) list: (m>n | nil | cons(m, f(m+1,n))); f(1,n));
  7.  
  8.   mode list = ref node;
  9.   mode node = struct (int h, list t);
  10.   proc cons = (int n, list l) list: heap node := (n,l);
  11.   proc hd   = (list l) int: ( l is nil | error("hd nil"); skip | h of l );
  12.   proc tl   = (list l) list: ( l is nil | error("tl nil"); skip | t of l );
  13.   proc show = (list l) void: ( l isnt nil | print((" ",whole(hd(l),0))); show(tl(l)));
  14.  
  15.   proc filter = (proc (int) bool p, list l) list:
  16.      if l is nil then nil
  17.      elif p(hd(l)) then cons(hd(l), filter(p,tl(l)))
  18.      else filter(p, tl(l))
  19.      fi;
  20.  
  21.   proc sieve = (list l) list:
  22.      if l is nil then nil
  23.      else
  24.         proc not multiple = (int n) bool: n mod hd(l) 0;
  25.         cons(hd(l), sieve( filter( not multiple, tl(l) )))
  26.      fi;
  27.  
  28.   proc primes = (int n) list: sieve( tl( one to(n) ));
  29.  
  30.   show( primes(100) )
  31. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement