Monday, March 21, 2016

Haskell Functions and Lists

Haskell is a quick and easy install on Windows and the Mac. The book, "Learn You a Haskell For Great Good!", is a quick and easy way to get started with the language.

Start the interpreter and set the prompt:
C:\> ghci
Prelude> :set prompt "ghci> "
ghci>  
Prelude> let first x = head x
Prelude> first ['a', 'b', 'c', 'd']
'a'
Prelude> let myList = ['a', 'b', 'c', 'd']
Prelude> first myList
'a'
Prelude> tail myList
"bcd"
Prelude> 
Prelude> 'a': ' ' : "small cat"
"a small cat"
Prelude> "a " ++ "small cat"
"a small cat"
Prelude> tail "a " ++ "small cat"
" small cat"
Prelude> init "a " ++ "small cat"
"asmall cat"
Prelude> init ("a " ++ "small cat")
"a small ca"
Prelude>
Prelude> let doubleMe x = x + x
Prelude> doubleMe 4
8
Prelude> let doubleUs x y = doubleMe x + doubleMe y
Prelude> doubleUs 7 3
20
Prelude>
In ghci, the Haskell REPL, 'let' is necessary to define a name but 'let' is not necessary in a script.
Prelude> let boomBang =[if x `mod` 2 == 0 then "BANG!" else "BOOM!" | x <- [1 .. 10]]
Prelude> boomBang
["BOOM!","BANG!","BOOM!","BANG!","BOOM!","BANG!","BOOM!","BANG!","BOOM!","BANG!"]
Prelude>
Prelude> let myCharData = "Now is The Time For All Good Men to Come to The AID of THEIR cOunTry"
Prelude> let removeUpper st = [c | c <- st, c `elem` ['a' .. 'z']]
Prelude> removeUpper myCharData
"owisheimeorlloodentoometoheofcunry"
Prelude>
Prelude> let myCharData = "Now is The Time For All Good Men to Come to The AID of THEIR cOunTry"
Prelude> let removeUpper st = [c | c <- st, c `elem` ' ': ['a' .. 'z']]
Prelude> removeUpper myCharData
"ow is he ime or ll ood en to ome to he  of  cunry"
Prelude>
Lists:
Prelude> take 10 [1..]
[1,2,3,4,5,6,7,8,9,10]
Prelude> take 10 [33..]
[33,34,35,36,37,38,39,40,41,42]
Prelude> take 10 ['a'..]
"abcdefghij"
Prelude> [3.0, 2.75..0]
[3.0,2.75,2.5,2.25,2.0,1.75,1.5,1.25,1.0,0.75,0.5,0.25,0.0]
Prelude> take 10 [1.0, 1.25..]
[1.0,1.25,1.5,1.75,2.0,2.25,2.5,2.75,3.0,3.25]
Prelude>
Tell ghci to print type information:
Prelude> 'c'
'c'
Prelude> :set +t
Prelude> 'c'
'c'
it :: Char
Prelude> :unset +t
Prelude>
Ratios
Prelude> 11 % 29

:12:4: Not in scope: `%'

Prelude> :m +Data.Ratio
Prelude Data.Ratio> 11 % 29
11 % 29
Prelude Data.Ratio> :set +t
Prelude Data.Ratio> 11 % 29
11 % 29
it :: Integral a => Ratio a
Prelude Data.Ratio>