teaching machines

CS 330 Lecture 23 – Guards, Tail Recursion, and Higher-order Functions

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

Agenda

TODO

Program This

  1. Write a function isIn that accepts to parameters: a list and an item. It returns true if the item appears in the last and false otherwise.
  2. Write a function named eachLower that takes a string parameter (a [Char]) and returns a lowercase version of the string. There’s a function toLower in the Data.Char module that converts a single character to lowercase.

Code

today.hs

import Data.Char

replicate' item 0 = []
replicate' item n = item:replicate' item (n - 1)

isIn [] needle = False
-- isIn haystack needle = if head haystack = needle then True else isIn (tail haystack) needle 
-- isIn (first:rest) needle = if first = needle then True else isIn rest needle 
isIn (first:rest) needle
  | first == needle = True
  | otherwise = isIn rest needle
-- isIn (first:rest) needle = first == needle || isIn rest needle 

eachLower [] = []
eachLower (first:rest) = toLower first:eachLower rest

eachMult10 [] = []
eachMult10 (first:rest) = first * 10:eachMult10 rest

eachDecapitate [] = []
eachDecapitate ((first:_):rest) = first:eachDecapitate rest

map' f [] = []
map' f (first:rest) = f first:map' f rest

eachLower' list = map' toLower list

-- mult10 a = 10 * a 
-- eachMult10' list = map' mult10 list 
eachMult10' list = map' (\a -> 10 * a) list
-- eachMult10' list = map' (*10) list

eachDecapitate' list = map' head list

filter' f [] = []
filter' f (first:rest)
  | f first = first:filter' f rest
  | otherwise = filter' f rest

Haiku

First-class citizens?!
First they are denied a name.
Then executed!