
The lenses book for Haskell and other functional programming languages by @chrislpenner https://xitter.gq/t.co/HOXV9Vvkt5
- Tweets85
- Following1
- Followers448
- Likes26

ALT _DividedBy :: Int -> Prism' Int Int _DividedBy n = prism' embed match where embed x = x * n match x | x `mod` n == 0 = Just (x `div` n) | otherwise = Nothing >>> 12 ^? _DividedBy 3 Just 4 >>> 12 ^? _DividedBy 5 Nothing >>> 12 ^? _DividedBy 3 . _DividedBy 4 Just 1 >>> _DividedBy 3 # 4 12 >>> _DividedBy 6 # 2 12

ALT _DividedBy :: Int -> Prism' Int Int _DividedBy n = prism' embed match where embed x = x * n match x | x `mod` n == 0 = Just (x `div` n) | otherwise = Nothing fizzbuzz :: Int -> String fizzbuzz = show & outside (_DividedBy 3) . mapped .~ "Fizz" & outside (_DividedBy 5) . mapped .~ "Buzz" & outside (_DividedBy 15) . mapped .~ "FizzBuzz" >>> traverse_ (putStrLn...

ALT import Control.Lens -- Our error type data Err = Err String deriving Show -- We have a handler for errors, but want one for strings too! errHandler :: Either Err a -> IO a errHandler = either (fail . show) return -- We can use outside to select the sub-function -- which operates on the Left side; e.g. `String -> IO a` stringHandler :: Either String a -> IO a stringHandler = errHandler & outside _Left . arg...
![-- BAD! >>> tail [] *** Exception: Prelude.tail: empty list -- Set the return value of the function to [] -- when the argument is empty: safeTail :: [a] -> [a] safeTail = tail & outside _Empty . mapped .~ [] >>> safeTail [] [] >>> safeTail [1, 2, 3] [2,3] >>> tail [] *** Exception: Prelude.tail: empty list](https://pbs.twimg.com/media/EGy0woXVAAAyjfp.jpg?name=small&format=webp)
ALT -- BAD! >>> tail [] *** Exception: Prelude.tail: empty list -- Set the return value of the function to [] -- when the argument is empty: safeTail :: [a] -> [a] safeTail = tail & outside _Empty . mapped .~ [] >>> safeTail [] [] >>> safeTail [1, 2, 3] [2,3] >>> tail [] *** Exception: Prelude.tail: empty list
![You can use *most* optics as though they're a custom `traverse` >>> (each . _Right) print (Left 1, Right 2, Left 3) 2 -- We can ignore the new structure it returns (Left 1,Right (),Left 3) It works on other types of effects too! Here we use lists as a non-determinism effect to get all possible combos! >>> each (\x -> [x, x+5]) (0, 10) [(0,10),(0,15),(5,10),(5,15)] -- Helper safeHead :: [a] -> Maybe a safeHead ...](https://pbs.twimg.com/media/EGC-Z5_UUAIOVOf.jpg?name=small&format=webp)
ALT You can use *most* optics as though they're a custom `traverse` >>> (each . _Right) print (Left 1, Right 2, Left 3) 2 -- We can ignore the new structure it returns (Left 1,Right (),Left 3) It works on other types of effects too! Here we use lists as a non-determinism effect to get all possible combos! >>> each (\x -> [x, x+5]) (0, 10) [(0,10),(0,15),(5,10),(5,15)] -- Helper safeHead :: [a] -> Maybe a safeHead ...




