Skip to content

Instantly share code, notes, and snippets.

@ThomasLocke
Created July 3, 2015 14:06
Show Gist options
  • Save ThomasLocke/22bd5c62bd5f07633871 to your computer and use it in GitHub Desktop.
Save ThomasLocke/22bd5c62bd5f07633871 to your computer and use it in GitHub Desktop.
Lad os tælle ting i lister af ting!
-- Skriv en funktion der returnerer strengen:
-- This is an amazingly interesting sentence!
???
-- Skriv en funktion der returnerer hvor mange gange a findes i [a]
countSomething :: Eq a => a -> [a] -> Int
countSomething ???
-- Skriv ovenstående funktion i 3 udgaver:
-- 1. En der løser opgaven med list comprehension
-- 2. En der løser opgaven med filter
-- 3. En der løser opgaven med foldl
-- Skriv en funktion der returnerer hvor mange gange Char findes i String
countChar :: Char -> String -> Int
countChar ???
@Tomren3000
Copy link

sentence :: String
sentence = "This is an amazingly interesting sentence!"

-- [noget] -> noget -> antal af noget
-- [a] -> a -> int
countSomething :: Eq a => a -> [a] -> Int
countSomething a as = length [x | x <- as, x == a]

countSomething' :: Eq a => a -> [a] -> Int
countSomething' a = length $ filter (a==)

countSomething'' :: Eq a => a -> [a] -> Int
countSomething'' a as = foldl (\acc x -> if x == a then acc + 1 else acc) 0 as

-- Skriv en funktion der returnerer hvor mange gange Char findes i String
countChar :: Char -> String -> Int
countChar = countSomething

countInt :: Int -> [Int] -> Int
countInt = countSomething

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment