Skip to content

Instantly share code, notes, and snippets.

@vlas-ilya
Created October 12, 2015 05:50
Show Gist options
  • Save vlas-ilya/2b5dd7a133f9509286c3 to your computer and use it in GitHub Desktop.
Save vlas-ilya/2b5dd7a133f9509286c3 to your computer and use it in GitHub Desktop.
Работа со списками в Haskell
import Data.Char
import Data.List
readDigits :: String -> (String, String)
readDigits = span isDigit
filterDisj :: (a -> Bool) -> (a -> Bool) -> [a] -> [a]
filterDisj f g = filter (\x -> f x || g x)
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (x:xs) = qsort [a | a <- xs, a < x] ++ [x] ++ qsort [a | a <- xs, a >= x]
squares'n'cubes :: Num a => [a] -> [a]
squares'n'cubes xs = concatMap (\x -> [x * x, x * x * x]) xs
perms :: Eq a => [a] -> [[a]]
perms [] = [[]]
perms xs = xs >>= perms'
where perms' x = map (\ys -> x:ys) $ perms [y | y <- xs, y /= x]
delAllUpper :: String -> String
delAllUpper = unwords . filter (not . (all isUpper)) . words
max3 :: Ord a => [a] -> [a] -> [a] -> [a]
max3 = zipWith3 (\a b c -> maximum [a, b, c])
fibStream :: [Integer]
fibStream = [0] ++ (zipWith (+) (fibStream) (1:fibStream))
data Odd = Odd Integer
deriving (Eq, Show)
instance Enum Odd where
toEnum n | odd n = (Odd $ toInteger n)
| otherwise = error "Not odd value"
fromEnum (Odd n) = fromInteger n
enumFrom (Odd n) = [(Odd n), (Odd (n + 2)) ..]
enumFromTo (Odd a) (Odd b) = [(Odd a), (Odd (a + 2)) .. (Odd b)]
succ (Odd n) = (Odd $ n + 2)
pred (Odd n) = (Odd $ n - 2)
coins :: (Ord a, Num a) => [a]
coins = [2, 3, 7]
change :: (Ord a, Num a) => a -> [[a]]
change n = change''
where change' = chang' n
change'' = if change' == [[]] then [] else change'
chang' :: (Ord a, Num a) => a -> [[a]]
chang' n | n < minimum coins = [[]]
| otherwise = [xs | x <- coins,
x <= n,
xs <- map (\ys -> x:ys) $ chang' (n - x),
sum xs == n]
meanList :: [Double] -> Double
meanList xs = (fst result) / (snd result)
where
result = foldr (\a (f, s) -> (f + a, s + 1)) (0, 0) xs
evenOnly :: [a] -> [a]
evenOnly xs = map fst result
where
xs' = zip xs [1..]
result = foldr (\(f,s) r -> if even s then (f, s):r else r) [] xs'
lastElem :: [a] -> a
lastElem = foldl1 (\_ b -> b)
revRange :: (Char, Char) -> [Char]
revRange = unfoldr g
where g (x, y) = if x <= y then Just (y, (x, pred y)) else Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment