7 ms·
Although this isn't OCAML, one thing I ended up missing when writing Haskell was F#'s Active Patterns.
by edgyswingset 11y ago
Although this isn't OCAML, one thing I ended up missing when writing Haskell was F#'s Active Patterns.
- porges 11y agoThese exist in Haskell as "Pattern Synonyms". Here's a partial translation of some of the F# examples on MSDN to Haskell; {-# LANGUAGE PatternSynonyms, ViewPatterns #-} pattern Even <- ((`mod` 2) -> 0) pattern Odd <- ((`mod` 2) -> 1) testNumber x = show x ++ case x of Even -> " is even" Odd -> " is odd" data Color = Color { r :: Int, g :: Int, b :: Int } pattern RGB r g b = Color r g b -- NB: this is bidirectional automatically printRGB :: Color -> IO () printRGB (RGB r g b) = print $ "Red: " ++ show r ++ " Green: " ++ show g ++ " Blue: " ++ show b -- pretend we have functions to and from RGB and HSV representation toHSV :: Color -> (Int, Int, Int) toHSV = undefined -- implement this yourself! fromHSV :: Int -> Int -> Int -> Color fromHSV = undefined pattern HSV h' s' v' <- (toHSV -> (h', s', v')) -- here we explicitly provide an inversion where HSV = fromHSV printHSV :: Color -> IO () printHSV (HSV h s v) = print $ "Hue: " ++ show h ++ " Saturation: " ++ show s ++ " Value: " ++ show v -- demonstrating being able to use pattern -- to construct a value addHue :: Int -> Color -> Color addHue n (HSV h s v) = HSV (h + n) s v