- Create an empty list:
emptyList = []
- Prepend an element to the list:
prepend = 10 : []
- Create a list of five integers:
list5 = 1 : 2 : 3 : 4 : 5 : []
- Create a list of integers from 1 to 10:
list10 = [1..10]
- Create an infinite list:
infiniteList = [1..]
- This is the head of a list:
getHead = head [1..10]
- This is the tail of a list:
getTail = tail [1..10]
- This is all but the last element:
allbutlast = init [1..10]
- Take 10 elements:
take10 = take 10 [1..]
- Drop 10 elements:
drop10 = drop 10 [1..20]
- Get nth element:
get1331th = [1..] !! 1331
- Check if a value is the element of the list.
is10element = elem 10 [1..10]
- Do pattern matching on the list. Here we check whether the list is empty or not:
isEmpty [] = True
isEmpty _ = False
- Do more pattern matching. Here we do pattern matching on elements present in the list.
isSize2 (x:y:[]) = True
isSize2 _ = False
- Concatenate two lists:
cat2 = [1..10] ++ [11..20]
- String is actually a list. Check this by creating a list of characters:
a2z = ['a'..'z']
- Since string is a list, we can use all list functions on string. Here we get the first character of a string:
strHead = head "abc"
- Zip two lists:
zip2 = zip ['a'..'z'] [1.. ]
- Open app/Main.hs and use the preceding functions from the list, and also print values:
module Main where
import Lib
main :: IO ()
main = do
putStrLn $ show $ (emptyList :: [Int])
putStrLn $ show $ prepend
putStrLn $ show $ list5
putStrLn $ show $ list10
putStrLn $ show $ getHead
putStrLn $ show $ getTail
putStrLn $ show $ allbutlast
putStrLn $ show $ take10
putStrLn $ show $ drop10
putStrLn $ show $ get1331th
putStrLn $ show $ is10element
putStrLn $ show $ isEmpty [10]
putStrLn $ show $ isSize2 []
putStrLn $ show $ cat2
putStrLn $ show $ a2z
putStrLn $ show $ strHead
- Build the project using stack build and run it using stack run list-functions-exe. Note that Main does not use the infiniteList snippets and does not print them.