Useful Idioms that will blow your mind (unless you already know them :)

This collection is supposed to be comprised of short, useful, cool, magical examples, which should incite the reader's curiosity and (hopefully) lead him to a deeper understanding of advanced Haskell concepts. At a later time I might add explanations to the more obscure solutions. I've also started providing several alternatives to give more insight into the interrelations of solutions.

More examples are always welcome, especially "obscure" monadic ones.

## List/String Operations

```  -- split at whitespace
-- "hello world" -> ["hello","world"]
words

takeWhile (not . null) . unfoldr (Just . (second \$ drop 1) . break (==' '))
-- there is a bug in this code in that two spaces in a row causes it to ignore the rest of the String
-- "hello  world" -> ["hello"]
-- sorry my Haskell isn't good enough to fix it!

fix (\f l -> if null l then [] else let (s,e) = break (==' ') l in s:f (drop 1 e))

-- splitting in two (alternating)
-- "1234567" -> ("1357", "246")
-- the lazy match with ~ is necessary for efficiency, especially enabling processing of infinite lists
foldr (\a ~(x,y) -> (a:y,x)) ([],[])

(map snd *** map snd) . partition (even . fst) . zip [0..]

transpose . unfoldr (\a -> toMaybe (null a) (splitAt 2 a))
-- this one uses the solution to the next problem in a nice way :)

toMaybe b x = if b then Just x else Nothing

-- splitting into lists of length N
-- "1234567" -> ["12", "34", "56", "7"]
unfoldr (\a -> toMaybe (null a) (splitAt 2 a))

takeWhile (not . null) . unfoldr (Just . splitAt 2)

-- sorting by a custom function
-- length -> ["abc", "ab", "a"] -> ["a", "ab", "abc"]
comparing f x y = compare (f x) (f y)
sortBy (comparing length)

map snd . sortBy (comparing fst) . map (length &&& id)
-- the so called "Schwartzian Transform" for computationally more expensive
-- functions.

rises xs = zipWith (<) xs (tail xs)

-- lazy substring search
-- "ell" -> "hello" -> True
substr a b = any (a `isPrefixOf`) \$ tails b

-- multiple splitAt's:
-- splitAts [2,5,0,3] [1..15] == [[1,2],[3,4,5,6,7],[],[8,9,10],[11,12,13,14,15]]
splitAts = foldr (\n r -> splitAt n >>> second r >>> uncurry (:)) return
```

## Mathematical Sequences, etc

```  -- factorial
-- 6 -> 720
product [1..6]

foldl1 (*) [1..6]

(!!6) \$ scanl (*) 1 [1..]

fix (\f n -> if n <= 0 then 1 else n * f (n-1))

-- powers of two sequence
iterate (*2) 1

unfoldr (\z -> Just (z,2*z)) 1

-- fibonacci sequence
unfoldr (\(f1,f2) -> Just (f1,(f2,f1+f2))) (0,1)

fibs = 0:1:zipWith (+) fibs (tail fibs)

fib = 0:scanl (+) 1 fib

-- pascal triangle
pascal = iterate (\row -> zipWith (+) ( ++ row) (row ++ )) 

-- prime numbers
-- example of a memoising caf (??)
primes = sieve [2..] where
sieve (p:x) = p : sieve [ n | n <- x, n `mod` p > 0 ]

unfoldr  sieve [2..] where
sieve (p:x) = Just(p,   [ n | n <- x, n `mod` p > 0 ])

-- or if you want to use the Sieve of Eratosthenes..
diff [] l = l
diff l [] = l
diff xl@(x:xs) yl@(y:ys) | x < y     = x:diff xs yl
| x > y     = diff xl ys
| otherwise = diff xs ys
esieve [] = []
esieve (p:ps) = p:esieve (diff ps (iterate (+p) p))
eprimes = esieve [2..]

-- enumerating the rationals (see )
rats :: [Rational]
rats = iterate next 1 where
next x = recip (fromInteger n+1-y) where (n,y) = properFraction x
```

```  -- all combinations of a list of lists.
-- these solutions are all pretty much equivalent in that they run
-- in the List Monad. the "sequence" solution has the advantage of
-- scaling to N sublists.
-- "12" -> "45" -> ["14", "15", "24", "25"]
sequence ["12", "45"]

[[x,y] | x <- "12", y <- "45"]

do { x <- "12"; y <- "45"; return [x,y] }

"12" >>= \a -> "45" >>= \b -> return [a,b]

-- all combinations of letters
(inits . repeat) ['a'..'z'] >>= sequence

-- apply a list of functions to an argument
-- even -> odd -> 4 -> [True,False]
map (\$4) [even,odd]

sequence [even,odd] 4

-- all subsequences of a sequence
filterM (const [True, False])

-- apply a function to two other function the same argument
--   (lifting to the Function Monad (->))
-- even 4 && odd 4 -> False
liftM2 (&&) even odd 4

liftM2 (>>) putStrLn return "hello"

-- forward function concatenation
(*3) >>> (+1) \$ 2

foldl1 (flip (.)) [(+1),(*2)] 500

-- perform functions in/on a monad, lifting
fmap (+2) (Just 2)

liftM2 (+) (Just 4) (Just 2)

-- [still to categorize]
(id >>= (+) >>= (+) >>= (+)) 3        -- (3+3)+(3+3) = 12

(join . liftM2) (*) (+3) 5            -- 64

mapAccumL (\acc n -> (acc+n,acc+n)) 0 [1..10] -- interesting for fac, fib, ...

do f <- [not, not]; d <- [True, False]; return (f d) -- [False,True,False,True]

do { Just x <- [Nothing, Just 5, Nothing, Just 6, Just 7, Nothing]; return x }
```

## Other

```  -- simulating lisp's cond
case () of () | 1 > 2     -> True
| 3 < 4     -> False
| otherwise -> True

-- match a constructor
-- this is better than applying all the arguments, because this way the
-- data type can be changed without touching the code (ideally).
case a of Just{} -> True
_      -> False

{-
TODO, IDEAS:
fun with arrows (second, first, &&&, ***)
liftM, ap
lazy search (searching as traversal of lazy structures)
innovative data types (i.e. having fun with Maybe sequencing)

bananas, envelopes, ...   (generic traversal)
why functional fp matters (lazy search, ...)
-}
```

### Polynomials

In abstract algebra you learn that polynomials can be used the same way integers are used given the right assumptions about their coefficients and roots. Specifically, polynomials support addition, subtraction, multiplication and sometimes division. It also turns out that one way to think of polynomials is that they are just lists of numbers (their coefficients).

``` instance Num a => Num [a] where               -- (1)
```
```   (f:fs) + (g:gs) = f+g : fs+gs               -- (2)
fs + [] = fs                                -- (3a)
[] + gs = gs                                -- (3b)
```
```   (f:fs) * (g:gs) = f*g : [f]*gs + fs*(g:gs)  -- (4)
_ * _ = []                                  -- (5)
```

#### Explanation

(1) puts lists into type class Num, the class to which operators + and * belong, provided the list elements are in class Num.

Lists are ordered by increasing powers. Thus f:fs means f+x*fs in algebraic notation. (2) and (4) follow from these algebraic identities:

``` (f+x*fs) + (g+x*gs) = f+g + x*(fs+gs)
(f+x*fs) * (g+x*gs) = f*g + x*(f*gs + fs*(g+x*gs))
```

(3) and (5) handle list ends.

The bracketed [f] in (4) avoids mixed arithmetic, which Haskell doesn't support.

```  [1, 1]^3 == [1, 3, 3, 1]
{"ft_lang_label":"__label__en","ft_lang_prob":0.76868707,"math_prob":0.9861803,"size":6969,"snap":"2022-27-2022-33","text_gpt3_token_len":2176,"char_repetition_ratio":0.08040201,"word_repetition_ratio":0.028059237,"special_character_ratio":0.37408525,"punctuation_ratio":0.15781711,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99528897,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-07-06T05:23:30Z\",\"WARC-Record-ID\":\"<urn:uuid:95cb60fa-2283-486f-ac26-b2749e028936>\",\"Content-Length\":\"46390\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:02419722-c1fd-415c-b34f-a400cb5cfea4>\",\"WARC-Concurrent-To\":\"<urn:uuid:ded109b3-0eab-482e-9138-8795b465b85f>\",\"WARC-IP-Address\":\"146.75.37.175\",\"WARC-Target-URI\":\"http://wiki.haskell.org/index.php?title=Blow_your_mind&oldid=10332\",\"WARC-Payload-Digest\":\"sha1:5YF3MZW36MP3UR64FHMXUAROYEGLO3GU\",\"WARC-Block-Digest\":\"sha1:BKLWRYE3MJ6NY647W6QAAJXITLTAYRDH\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-27/CC-MAIN-2022-27_segments_1656104660626.98_warc_CC-MAIN-20220706030209-20220706060209-00445.warc.gz\"}"}