Haskell Code Snippets: Functions, Lists, and File I/O Examples

Functions


--add5 :: Num a => a -> a
add5:: Double -> Double
add5 x=x+5

--Ex1
hello :: [Char] -> [Char]
hello s= "Hello "++s++" :D"

--Ex2
volume :: Num a => a -> a -> a -> a
volume x y z = x*y*z

--Ex3
doubleMe x= 2*x
myNumbers=[11..99]
myNumbers'=map doubleMe myNumbers
mod13 x = [k | k<-x,mod k 13==0]

--Ex4
initial n s =[head n] ++"."++[head s]++"."

--Ex5
unitaryN n= [[if j==i then 1 else 0 | j<- [1..n]] | i<- [1..n]]

--Ex6
list6 =[100*a+10*b+c |a<-[1..9],b<-[0..9],c<-[0..9], (a+b+c) `mod` 3==0, a/=b, a/=c,b/=c]

--Ex7
small s=[c | c<-s, c `elem` ['a'..'z']]
big s=[c | c<-s, c `elem` ['A'..'Z']]
nodig s=[c | c<-s, c `notElem` ['0'..'9']]

List Operations


--Ex1
charN n s= s !! (n-1)

--Ex2
listA=[("Ala", "Fox"), ("Thomas", "Cat"), ("Ola", "Wolf"), ("Piotr", "Bel"), ("Agata", "Gliwa"), ("Marek", "Pol")]
listB=[10*a+b | a<-[3,5,7], b<-[3,4]]
listA1 = fst (unzip listA)
listA2 =snd (unzip listA)
people= [(a,b,c)|a<-listA1,b<-listA2,c<-listB]

--Ex3
factors x =[n|n<-[1..x], mod x n ==0]
isPrime x = factors x==[1,x]

--Ex4
pair [] _ = (0,0) --first special case
pair _ [] = (0,0) --second special case
pair x y = (head x, last y)

--Ex5
sign x= if x>0 then 1 else (if x<0 then -1 else 0)

Recursive Functions


--Ex. 1.

c 1=1
c n =1 +2*c(n-1)

c15= [c n|n<-[1..15]]
c_n=[c n|n<-[1..]]
c1000 = takeWhile (<1000) c_n

--Ex2
a 0=1
a n = a (n-1) * b(n-1)
b 0=1
b n = a (n-1) + b(n-1)

a10= [a x|x<-[0..10]]

--Ex3
firstFromList (x:_)= x
firstFromList []=error "empty list"
secondFromList []=error "empty list"
secondFromList[_]=error"only one element"
secondFromList(_:x:_)=x
lastFromList []=error "empty list"
lastFromList[x]=x
lastFromList(x:xs)=lastFromList xs
prelastFromList[]=error"empty list"
prelastFromList[_]=error"one element"
prelastFromList[x,_]=x
prelastFromList(x:xs)=prelastFromList(xs)

--Ex4
mergeList [] =[]
mergeList (x:xs) = x++mergeList(xs)

--Ex5
howmanytimes x y= (length . filter (==x)) y

connectOneAfterOne [] x = x
connectOneAfterOne x [] = x
connectOneAfterOne (x:xs) (y:ys) = x:y:connectOneAfterOne xs ys

More List Functions


--Ex 1
sumPositive []=0
sumPositive (x:xs)=(if x>0 then x else 0)+sumPositive(xs)

--Ex2
count x []=0
count x (y:ys)=  (if x y ==True then 1 else 0)+count x (ys)

--Ex3
palin []=True
palin [x]=True
palin (x)= head x==last x && palin (tail (init x))

I/O Examples


sum_diff = do
  putStr "a=" -- printing a string
  a <- getLine  -- loading the entered line (String)
  putStr "b="  -- printing a string
  b <- getLine  -- loading the entered line (String)
  putStrLn  ("a+b="  ++ (show  ((read a ::Double) + (read b::Double))))
  putStrLn  ("a-b="  ++ (show  ((read a ::Double) - (read b::Double))))
  
-- read a ::Double  - reading a (String) and conversion to  Double type (analogous for b) to perform arithmetic operations
-- show (...)  - we use the result to be treated as a String to connect it to another String element    
-- call in ghci: sum_diff

-- the function sNTimes has no parameters
sNTimes = do
  putStr "Enter your string: "<br>
  s <- getLine
  putStr "How many times? n= "
  n <- getLine
  let n1=read n ::Int
  putStrLn (sn s n1) -- we use the  function sn defined below
  
-- the  function sn recursively builds a chain of n repetitions of the string s (separated by spaces)
sn s n  
  | n<0 = "Wrong n"
  | n==0 = ""
  | otherwise = s ++ " " ++ sn s (n-1)

File I/O


import System.IO      -- module import to work with IO operations
import Data.List      -- module import with functions for lists
import Data.Char      -- module import with functions for characters
--import System.Random   -- module import with random generators

--Ex1
myFile = do
  handle <-  openFile "C:\\Users\\Usuario\\Desktop\\file.txt" ReadMode --opening the file for reading, associated with the name handle, you can use a different own name
  contents <- hGetContents handle  --get content from handle, name contents can be replaced with your own name
  putStrLn contents  --printing content from contents
  hClose handle  --closing the file
 
--Ex2
write = do
  handle <- openFile "C:\\Users\\Usuario\\Desktop\\file.txt" WriteMode
  tekst <- getLine
  hPutStrLn  handle tekst
  hClose handle

--Ex3
fileToFile file1 file2 = do 
  contents <- readFile file1
  writeFile file2 (unlines . reverse . lines $ contents)
  
--Ex4
myRead = do
  putStrLn "Enter the name of the file"
  plik <- getLine  -- here we give the file name (with path) without quotation marks
  readLines plik
  readWords plik
  readChar plik

readLines fileName = do
  handle <- openFile fileName ReadMode
  contents <- hGetContents handle
  let number = length $ lines contents
  putStrLn ( "Number of lines = " ++ show number)
  hClose handle

readWords fileName = do
  handle <- openFile fileName ReadMode
  contents <- hGetContents handle
  let number = length $ words contents  -- the function words converts the text to a list of words
  putStrLn $ "Number of words = " ++show number
  hClose handle

readChar fileName = do
  handle <- openFile fileName ReadMode
  contents <- hGetContents handle
  let number = length $ filter isAlpha contents
  putStrLn $ "Number of letters = " ++show number
  let number = length $ filter (/=' ') contents
  putStrLn $ "number of characters different from spaces = " ++show number
  hClose handle