Nyt on käsitelty funktiot ja listat:
$ ghci
Prelude> let ts = [2,3,5,7,11,13]
Prelude> ts !! 4
11
Prelude> ts ++ [17,19]
[2,3,5,7,11,13,17,19]
Prelude> map negate ts
[-2,-3,-5,-7,-11,-13]
Prelude> map (+2) ts
[4,5,7,9,13,15]
Prelude> map (*2) ts
[4,6,10,14,22,26]
Prelude> take 4 ts
[2,3,5,7]
Prelude> take 8 (cycle [1,2])
[1,2,1,2,1,2,1,2]
Prelude> ts
[2,3,5,7,11,13]
Prelude> 9 `elem` ts
False
Prelude> 2 `elem` ts
True
Prelude> filter (<10) ts
[2,3,5,7]
Prelude> filter even ts
[2]
Prelude> let p = (2,5)
Prelude> fst p
2
Prelude> snd p
5
Prelude> ts
[2,3,5,7,11,13]
Prelude> head ts
2
Prelude> tail ts
[3,5,7,11,13]
Prelude> last ts
13
Prelude> let len = length
Prelude> len ts
6
Prelude> maximum ts
13
Prelude> minimum ts
2
Prelude> 2 `notElem` ts
False
Prelude> null []
True
Prelude> filter odd ts
[3,5,7,11,13]
Prelude> product ts
30030
Prelude> sum ts
41
Prelude> take 6 (repeat 2)
[2,2,2,2,2,2]
Prelude> replicate 5 3
[3,3,3,3,3]
Prelude> reverse ts
[13,11,7,5,3,2]
Prelude> splitAt 3 ts
([2,3,5],[7,11,13])
Prelude> take 4 ts
[2,3,5,7]
Prelude> let ns = [1..]
Prelude> take 10 ns
[1,2,3,4,5,6,7,8,9,10]
Prelude> takeWhile (<5) ns
[1,2,3,4]
Prelude> dropWhile (<5) ts
[5,7,11,13]
Prelude> take 6 (zip ns ts)
[(1,2),(2,3),(3,5),(4,7),(5,11),(6,13)]
Prelude>
Haskellin standardifunktiot ovat kirjastossa Prelude.hs. Tämä kirjasto ladataan oletuksena ghci:ssä. Luettelon standardikirjaston funktioista saat esimerkiksi ghci:llä komennolla ":browse Prelude":
$ ghci
Prelude> :browse Prelude
($!) :: (a -> b) -> a -> b
(!!) :: [a] -> Int -> a
($) :: (a -> b) -> a -> b
(&&) :: Bool -> Bool -> Bool
(++) :: [a] -> [a] -> [a]
(.) :: (b -> c) -> (a -> b) -> a -> c
... pitkän luettelon alku ja loppu ...
words :: String -> [String]
writeFile :: FilePath -> String -> IO ()
zip :: [a] -> [b] -> [(a, b)]
zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
(||) :: Bool -> Bool -> Bool
Prelude>
Luennoissa käytettiin funktiota toLower. Se ei kuulu standardikirjastoon. Miten löydämme sen? Yksi ratkaisu on asentaa ghci:hin hoogle-lisäosa.
Prelude> :hoogle toLower
Data.Char toLower :: Char -> Char
Data.Text toLower :: Text -> Text
Data.Text.Lazy toLower :: Text -> Text
Prelude> import Data.Char
Prelude Data.Char> [toLower x | x <- "XsTsNsXssTss"]
"xstsnsxsstss"