-- code_2009_03_02.hs
-- Glenn G. Chappell
-- 2 Mar 2009
--
-- For CS 331 Spring 2009
-- Sample Haskell code
-- From the Monday, March 2, 2009 class meeting

module Main where

import List  -- for sort


-- ---------------------------------------------------------------------
-- Code from topic Haskell: Lists & Loops
-- ---------------------------------------------------------------------


-- Anonymous ("Lambda") Functions

-- Doubling function
dubl x = 2*x
-- List of all even numbers 1..20
evens1 = map dubl [1..10]
-- Another way to do it, without using the named function
evens2 = map (\x -> 2*x) [1..10]


-- More on Fold

-- max (3 versions)
-- All 3 functions are given a list and return a list containing
-- its maximum item, or the empty list if the given list is empty

-- max_a uses sort, from the List module, which must be imported
-- (see above).
max_a xs = drop (length xs - 1) $ (sort xs)

-- max_b uses foldl. I imagine it is faster.
max_b xs = foldl maxh [] xs where
    maxh [] a = [a]
    maxh [x] a  | a < x      = [x]
                | otherwise  = [a]

-- max_c uses foldr.
max_c xs = foldr maxh [] xs where
    maxh a [] = [a]
    maxh a [x]  | a < x      = [x]
                | otherwise  = [a]


-- List Comprehensions

-- pythTrip: list of all Pythagorean triples
pythTrip = [(a,b,c) | c <- [1..], b <- [1..c-1], a <- [1..b-1], a^2+b^2 == c^2]

-- pythTrip_hang: does not work, due to multiple infinite lists
pythTrip_hang = [(a,b,c) | a <- [1..], b <- [1..], c <- [1..], a^2+b^2 == c^2]

-- pythTrip_fast: another working version, computes much faster
-- Uses a little number theory. Not in same order as above.
pythTrip_fast = [(x^2-y^2, 2*x*y, x^2+y^2) | x <- [1..], y <- [1..x-1]]

