teaching machines

CS 330 Lecture 27 – List Comprehensions and On To C++

April 10, 2013 by . Filed under cs330, lectures, spring 2013.

Agenda

TODO

Code

vowels.hs

data Vowel = A | E | I | O | U deriving (Show, Eq, Enum, Bounded)

listcomps.hs

powersOfTwo n = [2 ^ exponent | exponent <- [0..n]]
powersOfTwo' n = map (2^) [0..n]
decapitate lol = [head word | word <- lol]

waaaaaaaaaaaa.hs

import Control.Monad
import Control.Concurrent

linelength = 30
swirlfun = [replicate (fromIntegral (truncate (linelength * sin x + linelength))) '*' | x <- [1,1.05..200]]

main = do
  forM swirlfun (\line -> do
    putStrLn line
    threadDelay 10000
    return ())
  return ()

Functions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

class LinearFunction {
  public:
    LinearFunction(double slope, double y_intercept);
    double evaluateAt(double x);

  private:
    double slope;
    double y_intercept;
};

#endif

Functions.cpp

#include "Functions.h"

LinearFunction::LinearFunction(double slope,
                               double y_intercept) :
  slope(slope),
  y_intercept(y_intercept) {
}

double LinearFunction::evaluateAt(double x) {
  return slope * x + y_intercept;
}

graph.cpp

#include <iostream>
#include "Functions.h"

/* ------------------------------------------------------------------------- */

void draw(LinearFunction f);

int main(int argc, char **argv) {
  LinearFunction f(1.0, 0.0);
  draw(f);
  return 0;
}

/* ------------------------------------------------------------------------- */

void draw(LinearFunction f) {
  const int NROWS = 21;
  const int NCOLS = 51;

  char plot[NROWS][NCOLS];

  for (int r = 0; r < NROWS; ++r) {
    for (int c = 0; c < NCOLS; ++c) {
      plot[r][c] = ' ';
    }
  }

  for (int c = 0; c < NCOLS; ++c) {
    plot[NROWS / 2][c] = '-';
  }

  for (int r = 0; r < NROWS; ++r) {
    plot[r][NCOLS / 2] = '|';
  }

  plot[NROWS / 2][NCOLS / 2] = '+';

  for (int c = 0; c < NCOLS; ++c) {
    double x = c / (NCOLS - 1.0) * 6.0 - 3.0;
    double y = f.evaluateAt(x);
    int r = (int) (y * NROWS * 0.5 + NROWS * 0.5);
    if (r >= 0 && r < NROWS) {
      plot[r][c] = '.';
    }
  }

  for (int r = NROWS - 1; r >= 0; --r) {
    for (int c = 0; c < NCOLS; ++c) {
      std::cout << plot[r][c];
    }
    std::cout << std::endl;
  }
}

/* ------------------------------------------------------------------------- */

makefile

Note to copy and pasters: makefile rules need to be indented with real tabs, not spaces.

all: graph

Functions.cpp: Functions.h

Functions.o: Functions.cpp
  g++ -c Functions.cpp

graph: graph.cpp Functions.o Functions.h
  g++ -o graph graph.cpp Functions.o

run: run_graph
run_graph:
  ./graph

clean:
  rm -f *.o

Haiku

Knowing one language
Like using just a hammer
It makes for loud meals
Errors and classes
What happens when they marry?
Objections are raised