20-CS-4003-001 Organization of Programming Languages Fall 2017

Lambda calculus, Type theory, Formal semantics, Program analysis

    Previous     Next     All lectures        Code    

Fibonacci Numbers

import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.math.*;

// Stream declaration 
class Stream {
   public Stream () { isNull = true; }
   public boolean isNull;
   public BigInteger first;
   public Stream rest () { return null; }

// Fibonacci numbers
class Fibonacci extends Stream {
   BigInteger last, nxt_to_last;

   public Fibonacci (BigInteger a, BigInteger b) {
      isNull = false;
      nxt_to_last = a;
      last = b;
      first = last;

   public Fibonacci rest () { 
         new Fibonacci(last,last.add(nxt_to_last)); 

class Stream_6Frame 
   extends JFrame implements ActionListener {
   JTextArea text;
   JButton go;
   Stream s;

   public Stream_6Frame () {
      setLayout(new BorderLayout());
      setBackground(new Color(255,255,223));
          new JScrollPane(text = new JTextArea()));
      JPanel p = new JPanel();
      p.setLayout(new FlowLayout());
      p.setBackground(new Color(255,255,223));
      p.add(go = new JButton("Next"));
      add("South", p);
          new JLabel("Fibonacci numbers", JLabel.LEFT));
      BigInteger one = new BigInteger("1");
      s = new Fibonacci(one, one);

   public void actionPerformed (ActionEvent evt) {
      int p = text.getDocument().getLength();
      s = s.rest();

public class stream_6 
   extends Applet implements ActionListener {
   JButton go;

   public void init () {
      setLayout(new BorderLayout());
      setBackground(new Color(255,255,223));
      add("Center", go = new JButton("Applet"));

   public void actionPerformed (ActionEvent evt) {
      Stream_6Frame sf = new Stream_6Frame();
 -  The class Fibonacci to the left computes a stream of Fibonacci numbers. The red lines on the left show where the output stream is referenced by s. Walking through s is done as in the previous slide.