packages feed

caseof (empty) → 0.0.0

raw patch · 5 files changed

+201/−0 lines, 5 filesdep +basedep +template-haskellsetup-changed

Dependencies added: base, template-haskell

Files

+ LICENSE view
@@ -0,0 +1,30 @@+Copyright Chris Done (c) 2018++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of Chris Done nor the names of other+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,63 @@+# caseof++A simple way to query constructors, like cases but slightly more+concise.++Aimed at sum types with many constructors:++``` haskell+data Wiggle = Woo Int Char | Wibble Int deriving Show+```++There is a case predicate:++``` haskell+> $(isCaseOf 'Woo) (Woo 5 'a')+True+```++There is a `Maybe`-based matcher:++``` haskell+> $(maybeCaseOf 'Woo) (Woo 1 'a')+Just (1,'a')+```++There is a combinator which calls your function with n arguments, or+passes the whole value to an "else" clause.++``` haskell+> $(caseOf 'Woo) (\x y -> show x ++ show y) (const "") (Wibble 5)+""+```++This allows them to be nested:++```haskell+> $(caseOf 'Woo) (\x y -> show x ++ show y) (const "") (Woo 5 'a')+"5'a'"+> $(caseOf 'Woo) (\x y -> show x ++ show y) ($(caseOf 'Wibble) show (const "")) (Woo 5 'a')+"5'a'"+```++What's the point of `caseOf`? To more easily dispatch on functions:++```haskell+handleHuman name age = ...+handleMachine id = ..+handleWithDefault def =+   $(caseOf 'Human) handleHuman .+   $(caseOf 'Machine) handleMachine def+```++This applies to any kind of "case" that you'd like to refactor into a function.++## Use in your project++In your stack.yaml, put:++```+extra-deps:+- git: https://github.com/chrisdone/caseof.git+  commit: 9a7f6bb+```
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ caseof.cabal view
@@ -0,0 +1,25 @@+name:                caseof+version:             0.0.0+synopsis:            Combinators for casing on constructors+description:         Template-Haskell-based combinators that let you select on constructors.+homepage:            https://github.com/chrisdone/caseof#readme+license:             BSD3+license-file:        LICENSE+author:              Chris Done+maintainer:          chrisdone@gmail.com+copyright:           2018 Chris Done+category:            Development+build-type:          Simple+extra-source-files:  README.md+cabal-version:       >=1.10++library+  hs-source-dirs:      src+  ghc-options:         -Wall+  exposed-modules:     CaseOf+  build-depends:       base >= 4.7 && < 5, template-haskell+  default-language:    Haskell2010++source-repository head+  type:     git+  location: https://github.com/chrisdone/caseof
+ src/CaseOf.hs view
@@ -0,0 +1,81 @@+{-# OPTIONS_GHC -fno-warn-type-defaults #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE TemplateHaskell #-}++module CaseOf where++import Language.Haskell.TH+import Language.Haskell.TH.Syntax++-- | Create a predicate that returns true if its argument is the given constructor.+isCaseOf :: Name -> Q Exp+isCaseOf input = do+  name <- nameAsValue input+  pure+    (LamCaseE+       [ Match (RecP name []) (NormalB (ConE 'True)) []+       , Match WildP (NormalB (ConE 'False)) []+       ])++-- | Return Just (x, y, ..) for the constructor C x y .., or Nothing.+maybeCaseOf :: Name -> Q Exp+maybeCaseOf input = do+  name <- nameAsValue input+  info <- reify name+  case info of+    DataConI _ ty _ ->+      pure+        (LamCaseE+           [ Match+               (ConP name (map patI [1 .. arity ty]))+               (NormalB (AppE (ConE 'Just) (TupE (map varI [1 .. arity ty]))))+               []+           , Match WildP (NormalB (ConE 'Nothing)) []+           ])+    _ -> fail ("Invalid data constructor " ++ pprint input)+  where+    varI i = VarE (mkName ("v" ++ show i))+    patI i = VarP (mkName ("v" ++ show i))+    arity (ForallT _ _ t) = arity t+    arity (AppT (AppT ArrowT _) y) = 1 + arity y+    arity _ = 0++-- | Call a function with arguments from the constructor if it+-- matches, or pass it to the wildcard function.+caseOf :: Name -> Q Exp+caseOf input = do+  name <- nameAsValue input+  info <- reify name+  case info of+    DataConI _ ty _ ->+      pure+        (LamE [VarP f, VarP nil]+           (LamCaseE+              [ Match+                  (ConP name (map patI [1 .. arity ty]))+                  (NormalB (foldl AppE (VarE f) (map varI [1 .. arity ty])))+                  []+              , Match (VarP this) (NormalB (AppE (VarE nil) (VarE this))) []+              ]))+    _ -> fail ("Invalid data constructor " ++ pprint input)+  where+    f = mkName "f"+    this = mkName "this"+    nil = mkName "nil"+    varI i = VarE (mkName ("v" ++ show i))+    patI i = VarP (mkName ("v" ++ show i))+    arity (ForallT _ _ t) = arity t+    arity (AppT (AppT ArrowT _) y) = 1 + arity y+    arity _ = 0++-- | Return the name if it is a value constructor, otherwise lookup a+-- value name.+nameAsValue :: Name -> Q Name+nameAsValue name =+  if nameSpace name == Just DataName+    then pure name+    else do+      mname <- lookupValueName (nameBase name)+      case mname of+        Nothing -> fail ("Not in scope constructor " ++ pprint name)+        Just n -> pure n