Skip to content

Useful functions

kayhide edited this page Jul 28, 2016 · 6 revisions

print

print :: Show a => a -> IO ()
print = putStrLn . show
ghci> print [1..5]
[1,2,3,4,5]

on

import Data.Function
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
ghci> (compare `on` fst) (5, 2) (1, 8)
GT
ghci> (compare `on` snd) (5, 2) (1, 8)
LT

nub, nubBy

import Data.List
nub :: Eq a => [a] -> [a]
nubBy :: (a -> a -> Bool) -> [a] -> [a]
ghci> let ary = [1..5] ++ [3..8]
ghci> ary
[1,2,3,4,5,3,4,5,6,7,8]
ghci> nub ary
[1,2,3,4,5,6,7,8]
ghci> nubBy (\x y -> x `mod` 3 == y `mod` 3) ary
[1,2,3]
ghci> nubBy ((==) `on` (`mod` 3)) ary
[1,2,3]

Sum

newtype Sum a = Sum {getSum :: a} 	-- Defined in ‘Data.Monoid’
ghci> import Data.Foldable
ghci> :t fold
fold :: (Foldable t, Monoid m) => t m -> m
ghci> fold [Sum 1, Sum 2, Sum 3]
Sum {getSum = 6}
ghci> foldMap Sum [1..3]
Sum {getSum = 6}
ghci> Sum 3 `mappend` Sum 10
Sum {getSum = 13}
ghci> Sum 3 <> Sum 10
Sum {getSum = 13}

Product

newtype Product a = Product {getProduct :: a}
  	-- Defined in ‘Data.Monoid’
ghci> foldMap Product [1..4]
Product {getProduct = 24}
ghci> Product 3 <> Product 10
Product {getProduct = 30}

guard

import Control.Monad
guard :: GHC.Base.Alternative f => Bool -> f ()
ghci> :{
ghci| do
ghci|   x <- [1..5]
ghci|   pure x
ghci| :}
[1,2,3,4,5]
ghci> :{
ghci| do
ghci|   x <- [1..5]
ghci|   guard $ even x
ghci|   pure x
ghci| :}
[2,4]

replicateM

import Control.Monad
replicateM :: Monad m => Int -> m a -> m [a]
ghci> replicateM 2 [1..3]
[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
Clone this wiki locally