{"text": "{-# OPTIONS -O3 -optc-O3 -XFlexibleInstances #-}\n\nmodule Paraiso(\n  Architecture(..),\n  Dsl,\n  Expr(..),\n  Register(..),(=$),\n  compile,\n  parallel,\n  sequential,\n  cuda,\n  mesh\n)where\n\nimport Control.Monad.RWS\nimport Data.Complex\nimport Data.List\nimport Data.Maybe\n\n\nimport Util\nimport Debug\n\n\n\n\n\ntype VarID = String\ntype VarModifier = String -> String\nmodRegister::VarModifier\nmodRegister = (++ \"_reg\")\nmodDevice::VarModifier\nmodDevice = (++ \"_dev\")\nflagRegister = \"\"  --\"__shared__ \"\n\n\ndata Architecture = X86 | \n                    CUDA{numberOfGrids::Int, numberOfThreads::Int} |\n                    MPI Architecture deriving Eq\n\ndata Statement = Statement{funcName::String, phase::StatementType}\n\ndata StatementType = Alloc String | Store String | Free String |            \n              FuncCall String [String] [String] \n              deriving (Eq, Ord, Show, Read)\nfuncNameMain = \"main\"\n\ndata HardwareContext = Host | Device String deriving (Eq, Ord, Show, Read)\ndata Context = Context \n    {\n     precision::String,\n     freeVariable::VarID, storeModifier::VarModifier, allocModifier::VarModifier,\n     parallelDegree::Int,\n     architecture:: Architecture,\n     hardware::HardwareContext,\n     fogArgument::[String],\n     fogArgumentType::[String],\n     openHostParallel::[String],\n     closeHostParallel::[String],\n     memSendHD::[String],\n     memRecvHD::[String],\n     memSendDH::[String],\n     memRecvDH::[String]\n    } \n\n\ndata Expr a = \n    Imm a |\n    Rand a a | \n    Var VarID |\n    Add (Expr a) (Expr a) |\n    Sub (Expr a) (Expr a) |\n    Mul (Expr a) (Expr a) |\n    Div (Expr a) (Expr a) |\n    Abs (Expr a) |\n    Rec (Expr a) |\n    Sgn (Expr a) deriving (Eq, Ord, Show, Read)\n\ncompileExpr:: (Show a) => VarModifier -> Expr a -> String\ncompileExpr mo = c where\n    c (Imm a) = show a\n    c (Rand lo hi) = \"drand(\" ++ show lo ++ \" , \" ++ show hi ++ \")\"\n    c (Var v) = mo v \n    c (Add a b) = \"(\" ++ c a ++ \" + \" ++ c b ++ \")\"\n    c (Sub a b) = \"(\" ++ c a ++ \" - \" ++ c b ++ \")\"\n    c (Mul a b) = \"(\" ++ c a ++ \" * \" ++ c b ++ \")\"\n    c (Div a b) = \"(\" ++ c a ++ \" / \" ++ c b ++ \")\"\n    c (Abs a) = \"abs(\" ++ c a ++ \")\"\n    c (Rec a) = \"(1.0 / \" ++ c a ++ \")\"\n    c (Sgn a) = \"(\" ++ c a ++ \" >0?1:-1)\"\n\n\ninstance (Num t) => Num (Expr t) where\n    a + b = Add a b\n    a - b = Sub a b\n    a * b = Mul a b\n    abs a = Abs a\n    signum a = Sgn a\n    fromInteger i =  Imm (fromInteger i)\n\ninstance Fractional t => Fractional (Expr t) where\n    a / b = Div a b\n    recip a = Rec a\n    fromRational i = Imm (fromRational i)\n\ninstance Real t => Real (Expr t) where\n    toRational = undefined\n\ninstance Floating t => Floating (Expr t) where\n    pi = undefined\n    exp = undefined\n    log = undefined\n    sin = undefined\n    cos = undefined\n    asin = undefined\n    atan = undefined\n    acos = undefined\n    sinh = undefined\n    cosh = undefined\n    asinh = undefined\n    atanh = undefined\n    acosh = undefined\n\ninstance RealFloat t => RealFloat (Expr t) where\n    floatRadix = undefined\n    floatDigits = undefined\n    floatRange = undefined\n    decodeFloat = undefined\n    encodeFloat = undefined\n    isNaN = undefined\n    isInfinite = undefined\n    isDenormalized = undefined\n    isNegativeZero = undefined\n    isIEEE = undefined\n\ninstance RealFrac t => RealFrac (Expr t) where\n    properFraction = undefined\n\ntype Dsl a = RWS () [Statement] Context a\n\n\n\ntellA::[String] -> Dsl ()\ntellA xs = do\n  s <- get\n  case hardware s of\n    Host -> tellHA xs\n    Device fn -> tellDA fn xs\ntellS::[String] -> Dsl ()\ntellS xs = do\n  s <- get\n  case hardware s of\n    Host -> tellHS xs\n    Device fn -> tellDS fn xs\n\ntellHA :: [String] -> Dsl ()\ntellHA = tell.map (\\st -> Statement funcNameMain (Alloc st))\ntellHS :: [String] -> Dsl ()\ntellHS = tell.map (\\st -> Statement funcNameMain (Store st))\ntellHF :: [String] -> Dsl ()\ntellHF = tell.map (\\st -> Statement funcNameMain (Free st))\ntellDA :: String -> [String] -> Dsl ()\ntellDA fn = tell.map (\\st -> Statement fn (Free st))\ntellDS :: String -> [String] -> Dsl ()\ntellDS fn = tell.map (\\st -> Statement fn (Free st))\n\ngetVarName = do\n  let inc (h:ts) = (h:(show.(1+).read $ ts))\n  state <- get\n  let v = freeVariable state\n  put state{freeVariable = inc v}\n  return v\n\n\nclass Register a where\n    allocate :: Dsl a\n    store::a -> a -> Dsl ()\n    output::[a] -> Dsl ()    \n\n(=$) :: Register a => a -> a -> Dsl ()\n(=$) = store\ninfix 0 =$\n\n\n\n\n\n\ninstance Register (Expr Double) where\n    allocate = do\n      v <- getVarName\n      s <- get\n      let \n        am = allocModifier s\n        sm = storeModifier s\n        prec = precision s\n        arch = architecture s\n        parD = parallelDegree s\n      if hardware s == Host \n         then do\n           case arch of\n             X86 -> tellA [am v  ++\";\"]\n             CUDA{} -> do               \n               let \n                 vDev = modDevice v\n                 vSha  = modRegister v\n                 sos = \"sizeof(\" ++ prec ++ \")*\" ++ show parD\n               tellHA  [prec ++ \" *\" ++ v ++ \" = (\" ++prec ++ \"*) malloc(\" ++sos++ \");\"]\n               tellHA  [prec ++ \" *\" ++ vDev ++ \";\"]\n               tellHA  [\"cudaMalloc((void**) &\" ++ vDev ++\" ,\" ++ sos ++ \");\"]\n               s<-get\n               put s{\n                 memSendHD = (memSendHD s +:) $ \n                   \"cudaMemcpy(\" ++ vDev ++ \" , \" ++ v ++ \",\"\n                      ++ sos ++ \" , cudaMemcpyHostToDevice);\",\n                 memRecvHD = (memRecvHD s ++) $ \n                   [prec ++ \" \"++ flagRegister ++\" \" ++ vSha ++ \";\" , vSha ++ \" = \" ++ sm vDev ++ \";\"],\n                 memSendDH = (memSendDH s +:) $ \n                   sm vDev ++ \" = \" ++ vSha ++ \";\", \n                 memRecvDH = (memRecvDH s +:) $ \n                   \"cudaMemcpy(\" ++ v ++ \" , \" ++ vDev ++ \",\"\n                     ++ sos ++ \", cudaMemcpyDeviceToHost);\", \n                 fogArgument     = (fogArgument     s +:) $ vDev,\n                 fogArgumentType = (fogArgumentType s +:) $ prec ++  \" *\" ++  vDev\n               }\n         else do\n           tellA [prec ++ \" \" ++  am v ++\";\"]\n      return $ Var v\n    store addr expr = do\n      case addr of\n        Var v -> do\n                  s <- get\n                  let sm = storeModifier s\n                  tellS [sm v ++ \" = \" ++ compileExpr sm expr ++ \";\"]\n        _ -> error \"lhs is not a variable address.\"\n    output addrs = do\n      s <- get\n      let \n          sm = storeModifier s\n          fromVar ex = case ex of\n                       Var id -> sm id \n                       _      -> \"output is not a variable address.\"\n          statement = \n              unwords $\n              (++ [\"<< endl;\"] ) $\n              ([\"cout <<\"] ++ ) $\n              intersperse (\"<< \\\" \\\" <<\") $\n              map fromVar addrs\n      tellS [statement]      \n\n\n     \n\ninstance (RealFloat a, Register a) => Register (Complex a) where\n    allocate = do\n      r <- allocate\n      i <- allocate\n      return (r:+i)\n    store (tr:+ti) (sr:+si) = do\n      tmp <- allocate\n      store tmp sr\n      store ti si\n      store tr tmp\n    output = undefined\n\n\ncompile :: Architecture -> Dsl a-> String\ncompile arch a = code\n  where\n      (_,s,w) = runRWS a () initContext\n\n      initContext = Context\n            {\n             freeVariable = \"a1\",\n             storeModifier = id,\n             allocModifier = ((precision initContext ++ \" \") ++),\n             parallelDegree = 1,\n             architecture = arch, \n             hardware = Host,\n             precision = case arch of\n                           CUDA{} -> \"float\"\n                           _      -> \"double\",\n             fogArgument =[],\n             fogArgumentType =[],\n             openHostParallel = [],\n             closeHostParallel = [],\n             memSendHD = [],\n             memRecvHD = [],\n             memSendDH = [],\n             memRecvDH = []\n            }\n\n          \n      funcAndBodies = groupSort funcName $ w\n      funcCalls::[StatementType]\n      funcCalls = concatMap (\\st -> case st of\n                                   (Statement _ fc@FuncCall{}) -> [fc]\n                                   _ -> []) w\n      lookupFunc fn = case find (\\(FuncCall n _ _) -> n==fn) funcCalls of\n                 Just fc -> fc\n                 Nothing -> error $ \"function disappeared! \" ++ fn\n\n\n      code = unlines $ progHeader ++ concatMap buildFunc funcAndBodies\n             \n      buildFunc (fn, stmts) = let\n          (header,footer) = sandwich fn\n          mysort = sortBy (\\a b->f a `compare` f b) \n          f (Statement _ Alloc{})    = 1\n          f (Statement _ Store{})    = 2\n          f (Statement _ FuncCall{}) = 2\n          f (Statement _ Free{})     = 3\n        in header ++ (map peal $ mysort stmts) ++ footer\n\n\n      peal (Statement _ (Alloc s)) = s\n      peal (Statement _ (Store s)) = s\n      peal (Statement _ (Free  s)) = s\n      peal (Statement _ (FuncCall fn args argtypes)) \n          = fn ++ \"<<<grids,threads>>>(\" ++ (unwords . intersperse \",\") args ++ \");\"\n\n      progHeader = includes ++ utilfuncs\n      includes = \n        (++[\"using namespace std;\"]) $\n        map (\\fn -> \"#include <\" ++ fn ++ \">\") $\n        headers\n      headers = [\"iostream\", \"cstdlib\"] \n        ++ case arch of\n             CUDA{} -> [] -- [\"cutil.h\"]\n             _      -> []\n      utilfuncs = \n        [\n         \"double drand(double lo, double hi){\",\n         \"return lo + rand()/(double)RAND_MAX * (hi-lo);\",\n         \"}\"\n        ]\n\n      sandwich fn = if fn == funcNameMain then\n           ([\"int main(int argc, char **argv){\"]\n            ++ case arch of\n              CUDA{numberOfGrids = ng,  numberOfThreads = nt}\n                -> [\"dim3 grids(\" ++ show ng ++\");\",\n                         \"dim3 threads(\" ++ show nt ++\");\"]\n              _ -> []\n\n           , [\"return 0;\",\"}\"])\n        else\n            ([\"__global__ void \" ++ fn ++ \"(\" ++ (unwords $ intersperse \",\" $ att fn) ++ \"){\"]\n            , [\"}\"])\n        \n      --argumentTypeTable\n      att fn = let (FuncCall _ _ fat) = lookupFunc fn in fat\n\n\n\n       \n\nparallel size dsl = do\n  iv <- getVarName\n  state <- get\n  put $ state{\n              storeModifier = (++ (\"[\" ++ iv ++ \"]\")) . storeModifier state,\n              allocModifier = (++ (\"[\" ++ show size ++ \"]\")) . allocModifier state,\n              memRecvHD = (:memRecvHD state) $ \"int \" ++ iv ++ \" = blockIdx.x * gridDim.x + threadIdx.x;\"\n--              fogArgument = (:fogArgument state) $  iv, NEEDED_FOR_GREATER_LOOP\n--              fogArgumentType = (:fogArgumentType state) $ \"int \" ++ iv\n             }\n  let\n    open  = \"for(int \"++iv++\" = 0 ; \"++iv++\" < \" ++ show size ++ \" ; ++\"++iv++\"){\"\n    close = \"}\"\n  tellS [open]\n  do\n    state <- get\n    put $ state{\n            openHostParallel  = openHostParallel state ++ [open],\n            closeHostParallel = [close] ++ closeHostParallel state,\n            parallelDegree = size * parallelDegree state\n          } \n    dsl\n  tellS [close]\n  put state\n  return ()\n\n\nmesh::[Int] -> Dsl () -> Dsl ()\nmesh dimension dsl = do\n  state <- get\n  if architecture state /= X86 then \n      error \"hey we just don't support mesh on GPU right now\"\n    else do\n          ivs <- mapM (\\ _ -> getVarName) dimension \n          let \n              shell f = concat . map (\\str -> \"[\" ++ f str ++ \"]\")\n              is = [0..(length ivs-1)]\n              opens = [\"for(int \"++ivs!!i++\" = 0 ; \"\n                       ++ivs!!i++\" < \" ++ show (dimension!!i) ++ \" ; \"\n                       ++\"++\"++ivs!!i++\"){\" | i <- is]\n              closes = [\"}\" | i<-is]\n\n          state <- get\n          tellS opens\n          put $ state {\n                       storeModifier = (++ shell id ivs) . storeModifier state,\n                       allocModifier = (++ shell show dimension) . allocModifier state\n                      }\n          dsl\n          tellS closes\n          put state\n  return ()\n\n\n\nsequential size dsl = do\n  iv <- getVarName\n  tellS [\"for(int \"++iv++\" = 0 ; \"++iv++\" < \" ++ show size ++ \" ; ++\"++iv++\"){\"]\n  dsl\n  tellS [\"}\"]\n  return ()\n\ncuda dsl = do\n  s <- get\n  case architecture s of\n    CUDA{} -> if hardware s == Host then\n                  docuda s\n              else\n                  error \"you can't use cuda inside cuda\"\n    _      -> dsl \n  where\n    docuda s = do\n      fnvar <- getVarName\n      let fn = \"function_on_GPU_\" ++ fnvar\n      tellS $ closeHostParallel s\n      tellS $ memSendHD s\n      tellDS fn $ memRecvHD s\n      tell $ [Statement funcNameMain $ FuncCall fn (fogArgument s) (fogArgumentType s)]\n      do\n        put s{hardware = Device fn, storeModifier = modRegister, allocModifier = (flagRegister ++).modRegister}\n        dsl \n      put s\n      tellDS fn $ memSendDH s\n      tellS $ memRecvDH s\n      tellS $ openHostParallel s\n", "meta": {"hexsha": "a27ea3d613834ffa0b74dc4ccdae11142f714060", "size": 12714, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "attic/paraiso-2008-ODEsolver/Paraiso.hs", "max_stars_repo_name": "nushio3/Paraiso", "max_stars_repo_head_hexsha": "e9eaea7a8c7384ceb43f8761e4af2f9206a5bbc7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2015-02-09T22:41:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T07:13:43.000Z", "max_issues_repo_path": "attic/paraiso-2008-ODEsolver/Paraiso.hs", "max_issues_repo_name": "nushio3/Paraiso", "max_issues_repo_head_hexsha": "e9eaea7a8c7384ceb43f8761e4af2f9206a5bbc7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2016-09-30T07:17:17.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-30T07:17:17.000Z", "max_forks_repo_path": "attic/paraiso-2008-ODEsolver/Paraiso.hs", "max_forks_repo_name": "nushio3/Paraiso", "max_forks_repo_head_hexsha": "e9eaea7a8c7384ceb43f8761e4af2f9206a5bbc7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2015-05-15T01:41:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-18T17:41:56.000Z", "avg_line_length": 28.6997742664, "max_line_length": 111, "alphanum_fraction": 0.4887525562, "num_tokens": 3449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.1995380783911481}}
{"text": "{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n\n-- |\n-- Module      :  Test.Gen\n-- Copyright   :  (c) 2016 Drexel University\n-- License     :  BSD-style\n-- Maintainer  :  mainland@drexel.edu\n\nmodule Test.Gen (\n    withComplexTransform,\n    withModularTransform,\n\n    withLibltdl,\n    withDL\n  ) where\n\nimport Data.Complex\nimport Data.Modular\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Storable.Mutable as MV\nimport Control.Exception (bracket,\n                          bracket_)\nimport Control.Monad (when)\nimport Control.Monad.IO.Class (liftIO)\nimport qualified Data.ByteString.Lazy as B\nimport Data.Foldable (toList)\nimport qualified Data.Text.Lazy.Encoding as E\nimport Foreign.ForeignPtr (withForeignPtr)\nimport Foreign.LibLTDL\nimport Foreign.Ptr (FunPtr,\n                    Ptr)\nimport Foreign.Storable (Storable)\nimport GHC.TypeLits (KnownNat)\nimport System.Directory (getTemporaryDirectory)\nimport System.FilePath ((</>))\nimport System.IO (IOMode(..),\n                  hClose,\n                  openFile)\nimport System.IO.Temp (withTempDirectory)\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Process (callProcess)\nimport Text.PrettyPrint.Mainland (prettyLazyText,\n                                  prettyPragmaLazyText)\nimport Text.PrettyPrint.Mainland.Class\n\nimport qualified Spiral.Backend.C as C\nimport Spiral (Spiral,\n               runSpiralWith)\nimport Spiral.Config\nimport Spiral.Exp\nimport Spiral.SPL\nimport Spiral.SPL.Run\n\nwithComplexTransform :: Config\n                     -> String\n                     -> SPL (Exp (Complex Double))\n                     -> ((V.Vector (Complex Double) -> V.Vector (Complex Double)) -> IO a)\n                     -> IO a\nwithComplexTransform conf name e k =\n    withCompiledTransform conf name (Re e) $ \\fptr ->\n    k $ mkTransform (dynComplexTransform fptr)\n\nwithModularTransform :: KnownNat p\n                     => Config\n                     -> String\n                     -> SPL (Exp (\u2124/p))\n                     -> ((V.Vector (\u2124/p)-> V.Vector (\u2124/p)) -> IO a)\n                     -> IO a\nwithModularTransform conf name e k =\n    withCompiledTransform conf name e $ \\fptr ->\n    k $ mkTransform (dynModularTransform fptr)\n\nforeign import ccall \"dynamic\"\n    dynComplexTransform :: FunPtr (Ptr (Complex Double) -> Ptr (Complex Double) -> IO ())\n                        -> Ptr (Complex Double)\n                        -> Ptr (Complex Double)\n                        -> IO ()\n\nforeign import ccall \"dynamic\"\n    dynModularTransform :: FunPtr (Ptr (\u2124/p) -> Ptr (\u2124/p) -> IO ())\n                        -> Ptr (\u2124/p)\n                        -> Ptr (\u2124/p)\n                        -> IO ()\n\nmkTransform :: Storable a\n            => (Ptr a -> Ptr a -> IO ())\n            -> V.Vector a\n            -> V.Vector a\nmkTransform f x = unsafePerformIO $ do\n    my <- MV.new n\n    let (fptr_x, _) = V.unsafeToForeignPtr0 x\n    let (fptr_y, _) = MV.unsafeToForeignPtr0 my\n    withForeignPtr fptr_x $ \\ptr_x ->\n      withForeignPtr fptr_y $ \\ptr_y ->\n        f ptr_x ptr_y\n    V.freeze my\n  where\n    n = V.length x\n\nwithCompiledTransform :: (Typed a, Num (Exp a))\n                      => Config\n                      -> String\n                      -> SPL (Exp a)\n                      -> (FunPtr b -> IO c)\n                      -> IO c\nwithCompiledTransform conf fname e k = do\n    temp <- getTemporaryDirectory\n    withTempDirectory temp \"spiral\" $ \\path -> do\n        let dotc, dotso :: FilePath\n            dotc  = path </> fname ++ \".c\"\n            dotso = path </> fname ++ \".so\"\n        runSpiralWith conf $ do\n            t <- toProgram fname e\n            c <- C.evalCg $ C.cgProgram t\n            when True $ writeOutput dotc (toList c)\n        callProcess \"gcc\" [\"-o\", dotso, \"-fPIC\", \"-shared\", dotc]\n        withLibltdl [\".\"] $ withDL dotso $ \\h -> dlSym h fname >>= k\n\nwithLibltdl :: SearchPath -> IO a -> IO a\nwithLibltdl path k = bracket_ dlInit dlExit (dlSetSearchPath path >> k)\n\nwithDL :: String -> (DLHandle -> IO a) -> IO a\nwithDL lib = bracket (dlOpen (Just lib)) dlClose\n\nwriteOutput :: Pretty a\n            => FilePath\n            -> a\n            -> Spiral ()\nwriteOutput output x = do\n    linePragmas <- asksConfig (testDynFlag LinePragmas)\n    let pprint | linePragmas = prettyPragmaLazyText 80 . ppr\n               | otherwise   = prettyLazyText 80 . ppr\n    h <- liftIO $ openFile output WriteMode\n    liftIO $ B.hPut h $ E.encodeUtf8 (pprint x)\n    liftIO $ hClose h\n", "meta": {"hexsha": "7922ccccb17bc69366b8f0092894f7fd200b1248", "size": 4588, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/test/Test/Gen.hs", "max_stars_repo_name": "mainland/hspiral", "max_stars_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-05-21T21:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T04:48:25.000Z", "max_issues_repo_path": "src/test/Test/Gen.hs", "max_issues_repo_name": "mainland/hspiral", "max_issues_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/Test/Gen.hs", "max_forks_repo_name": "mainland/hspiral", "max_forks_repo_head_hexsha": "16cc5b9732286de38b89d1a983e64d23646a05d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7714285714, "max_line_length": 90, "alphanum_fraction": 0.5821708806, "num_tokens": 1134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.1992568069742338}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE InstanceSigs #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE FlexibleInstances    #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE IncoherentInstances  #-}\n{-# LANGUAGE StandaloneDeriving  #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\n\nmodule Data.Vector.Image.IO (\n  readImg\n, writeImg\n, writeBmp\n, writePng\n, writeJpeg\n) where\n\nimport Prelude hiding(map)\nimport qualified Prelude as P\nimport qualified Data.List as L\nimport Data.Vector.Storable hiding(forM_,map,replicate,fromList,toList,(!?),(!))\nimport Data.Maybe\nimport Numeric.LinearAlgebra.Data hiding (fromList,toList,(!))\nimport Numeric.LinearAlgebra.HMatrix hiding (fromList,toList,(!))\nimport qualified Data.Vector.Storable as V\nimport Foreign\nimport GHC.Real\nimport Foreign.C.String\nimport Foreign.C.Types\nimport qualified Control.Monad as C\nimport Data.Vector.Image.Color.RGB\nimport Data.Vector.Image.Image\n\ntype WriteImgFunc = Ptr CChar -- ^ Filename\n                 -> Ptr RGB8  -- ^ Image Vector\n                 -> CInt      -- ^ Width of Image\n                 -> CInt      -- ^ Height of Image\n                 -> IO CInt   -- ^ When write fails, this returns negative value. When success, this returns 0.\n\nforeign import ccall unsafe \"readImg\" c_readImg :: Ptr CChar -> Ptr (Ptr RGB8) -> Ptr CInt -> Ptr CInt -> IO CInt\nforeign import ccall unsafe \"&freeImg\" c_p_freeImg :: FunPtr(Ptr RGB8 -> IO ())\nforeign import ccall unsafe \"writeBmp\" c_writeBmp :: WriteImgFunc\nforeign import ccall unsafe \"writePng\" c_writePng :: WriteImgFunc\nforeign import ccall unsafe \"writeJpeg\" c_writeJpeg :: WriteImgFunc\n\nreadImg :: String  -- ^ Filename\n        -> IO (Either Int Image8)\nreadImg file = do\n  withCString file $ \\ cfile -> do\n    alloca $ \\cp -> do\n      alloca $ \\cw -> do\n        alloca $ \\ch -> do\n          r <- fmap fromIntegral $ c_readImg cfile cp cw ch\n          w <- fmap fromIntegral $ peek cw\n          h <- fmap fromIntegral $ peek ch\n          p <- peek cp :: IO (Ptr RGB8)\n          let n = w*h\n          fp <- newForeignPtr c_p_freeImg p\n          return $ if r < 0\n                   then Left r\n                   else Right $  Image w h (unsafeFromForeignPtr fp 0 n)\n\nwriteImg' :: WriteImgFunc -> String -> Image8 -> IO (Either Int ())\nwriteImg' func file (Image w h dat) = do\n  r <- fmap fromIntegral $ withCString file $ \\ cfile -> do\n    unsafeWith dat $ \\p -> do\n      func cfile p (fromIntegral w) (fromIntegral h)\n  return $ if r < 0 then Left r else Right ()\n\n\nwriteImg :: String   -- ^ Filename\n         -> Image8  -- ^ Image Data\n         -> IO (Either Int ())\nwriteImg file img | L.isSuffixOf \".bmp\" file = writeBmp file img\n                  | L.isSuffixOf \".BMP\" file = writeBmp file img\n                  | L.isSuffixOf \".png\" file = writePng file img\n                  | L.isSuffixOf \".Png\" file = writePng file img\n                  | L.isSuffixOf \".jpg\" file = writeJpeg file img\n                  | L.isSuffixOf \".JPG\" file = writeJpeg file img\n                  | otherwise = return $ Left (-1)\n\n\nwriteBmp :: String   -- ^ Filename\n         -> Image8  -- ^ Image Data\n         -> IO (Either Int ())\nwriteBmp = writeImg' c_writeBmp\n\nwriteJpeg :: String  -- ^ Filename\n          -> Image8 -- ^ Image Data\n          -> IO (Either Int ())\nwriteJpeg = writeImg' c_writeJpeg\n\nwritePng :: String  -- ^ Filename\n         -> Image8 -- ^ Image Data\n         ->  IO (Either Int ())\nwritePng = writeImg' c_writePng\n", "meta": {"hexsha": "e72e72c8624b90cdde4113ff021d0b3c8a478d2b", "size": 3603, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Vector/Image/IO.hs", "max_stars_repo_name": "junjihashimoto/img-vector", "max_stars_repo_head_hexsha": "5331c171337274398a29f6719587893466b4b5d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-29T04:04:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-29T04:04:04.000Z", "max_issues_repo_path": "Data/Vector/Image/IO.hs", "max_issues_repo_name": "junjihashimoto/img-vector", "max_issues_repo_head_hexsha": "5331c171337274398a29f6719587893466b4b5d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Data/Vector/Image/IO.hs", "max_forks_repo_name": "junjihashimoto/img-vector", "max_forks_repo_head_hexsha": "5331c171337274398a29f6719587893466b4b5d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6732673267, "max_line_length": 113, "alphanum_fraction": 0.6250346933, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.1980516930153985}}
{"text": "{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE RoleAnnotations #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE Trustworthy #-}\n{-# OPTIONS_GHC -Wno-orphans #-}\n----------------------------------------------------------------------------\n-- |\n-- Module      :  Control.Lens.Fold\n-- Copyright   :  (C) 2012-16 Edward Kmett\n-- License     :  BSD-style (see the file LICENSE)\n-- Maintainer  :  Edward Kmett <ekmett@gmail.com>\n-- Stability   :  provisional\n-- Portability :  Rank2Types\n--\n-- A @'Fold' s a@ is a generalization of something 'Foldable'. It allows\n-- you to extract multiple results from a container. A 'Foldable' container\n-- can be characterized by the behavior of\n-- @'Data.Foldable.foldMap' :: ('Foldable' t, 'Monoid' m) => (a -> m) -> t a -> m@.\n-- Since we want to be able to work with monomorphic containers, we could\n-- generalize this signature to @forall m. 'Monoid' m => (a -> m) -> s -> m@,\n-- and then decorate it with 'Const' to obtain\n--\n-- @type 'Fold' s a = forall m. 'Monoid' m => 'Getting' m s a@\n--\n-- Every 'Getter' is a valid 'Fold' that simply doesn't use the 'Monoid'\n-- it is passed.\n--\n-- In practice the type we use is slightly more complicated to allow for\n-- better error messages and for it to be transformed by certain\n-- 'Applicative' transformers.\n--\n-- Everything you can do with a 'Foldable' container, you can with with a 'Fold' and there are\n-- combinators that generalize the usual 'Foldable' operations here.\n----------------------------------------------------------------------------\nmodule Control.Lens.Fold\n  (\n  -- * Folds\n    Fold\n  , IndexedFold\n\n  -- * Getting Started\n  , (^..)\n  , (^?)\n  , (^?!)\n  , pre, ipre\n  , preview, previews, ipreview, ipreviews\n  , preuse, preuses, ipreuse, ipreuses\n\n  , has, hasn't\n\n  -- ** Building Folds\n  , folding, ifolding\n  , foldring, ifoldring\n  , folded\n  , folded64\n  , unfolded\n  , iterated\n  , filtered\n  , filteredBy\n  , backwards\n  , repeated\n  , replicated\n  , cycled\n  , takingWhile\n  , droppingWhile\n  , worded, lined\n\n  -- ** Folding\n  , foldMapOf, foldOf\n  , foldrOf, foldlOf\n  , toListOf, toNonEmptyOf\n  , anyOf, allOf, noneOf\n  , andOf, orOf\n  , productOf, sumOf\n  , traverseOf_, forOf_, sequenceAOf_\n  , traverse1Of_, for1Of_, sequence1Of_\n  , mapMOf_, forMOf_, sequenceOf_\n  , asumOf, msumOf\n  , concatMapOf, concatOf\n  , elemOf, notElemOf\n  , lengthOf\n  , nullOf, notNullOf\n  , firstOf, first1Of, lastOf, last1Of\n  , maximumOf, maximum1Of, minimumOf, minimum1Of\n  , maximumByOf, minimumByOf\n  , findOf\n  , findMOf\n  , foldrOf', foldlOf'\n  , foldr1Of, foldl1Of\n  , foldr1Of', foldl1Of'\n  , foldrMOf, foldlMOf\n  , lookupOf\n\n  -- * Indexed Folds\n  , (^@..)\n  , (^@?)\n  , (^@?!)\n\n  -- ** Indexed Folding\n  , ifoldMapOf\n  , ifoldrOf\n  , ifoldlOf\n  , ianyOf\n  , iallOf\n  , inoneOf\n  , itraverseOf_\n  , iforOf_\n  , imapMOf_\n  , iforMOf_\n  , iconcatMapOf\n  , ifindOf\n  , ifindMOf\n  , ifoldrOf'\n  , ifoldlOf'\n  , ifoldrMOf\n  , ifoldlMOf\n  , itoListOf\n  , elemIndexOf\n  , elemIndicesOf\n  , findIndexOf\n  , findIndicesOf\n\n  -- ** Building Indexed Folds\n  , ifiltered\n  , itakingWhile\n  , idroppingWhile\n\n  -- * Internal types\n  , Leftmost\n  , Rightmost\n  , Traversed\n  , Sequenced\n\n  ) where\n\nimport Prelude\nimport Data.List.NonEmpty (NonEmpty(..))\nimport qualified Data.List.NonEmpty as NonEmpty\nimport Control.Monad as Monad\nimport Control.Monad.Reader\nimport qualified Control.Monad.Reader as Reader\nimport Data.Functor\nimport Control.Monad.State\nimport Data.Int (Int64)\nimport Data.List (intercalate)\nimport Data.Maybe (fromMaybe, Maybe(..))\nimport Data.Monoid (First (..), All (..), Any (..), Endo (..), Dual(..), Monoid(..))\nimport qualified Data.Monoid as Monoid\nimport Data.Ord (Down(..))\nimport Data.Functor.Compose\nimport Data.Functor.Contravariant\nimport Control.Applicative\nimport GHC.Stack\nimport Control.Applicative.Backwards\nimport Data.Kind\nimport Data.Functor.Identity\nimport Data.Bifunctor\nimport Control.Arrow (Arrow, ArrowApply(..), ArrowChoice(..), ArrowLoop(..), (&&&), (***))\nimport qualified Control.Arrow as Arrow\nimport qualified Control.Category as C\nimport Control.Monad.Writer\nimport qualified Control.Monad.Trans.Writer.Lazy as Lazy\nimport qualified Control.Monad.Trans.Writer.Strict as Strict\nimport Control.Monad.Trans.Maybe\nimport Control.Monad.Trans.Except\nimport Data.Tree\nimport qualified Data.IntMap as IntMap\nimport qualified Data.Map as Map\nimport Data.Map (Map)\nimport qualified Control.Monad.State as State\nimport Control.Monad.Writer\nimport Data.Coerce\nimport qualified GHC.Generics as Generics\nimport GHC.Generics (K1(..), U1(..), Par1(..), (:.:)(..), Rec1, M1, (:*:)(..))\nimport Control.Monad.Trans.Cont\nimport qualified Data.Semigroup as Semi\nimport qualified Data.Semigroup as Semigroup\nimport Data.Complex\nimport Control.Monad.Trans.Identity\nimport qualified Data.Functor.Product as Functor\nimport Data.Proxy\nimport Data.Typeable\nimport Data.Ix\nimport Data.Foldable (traverse_)\n\ninfixr 9 #.\ninfixl 8 .#\n\n{- |\n\nThere are two ways to define a comonad:\n\nI. Provide definitions for 'extract' and 'extend'\nsatisfying these laws:\n\n@\n'extend' 'extract'      = 'id'\n'extract' . 'extend' f  = f\n'extend' f . 'extend' g = 'extend' (f . 'extend' g)\n@\n\nIn this case, you may simply set 'fmap' = 'liftW'.\n\nThese laws are directly analogous to the laws for monads\nand perhaps can be made clearer by viewing them as laws stating\nthat Cokleisli composition must be associative, and has extract for\na unit:\n\n@\nf '=>=' 'extract'   = f\n'extract' '=>=' f   = f\n(f '=>=' g) '=>=' h = f '=>=' (g '=>=' h)\n@\n\nII. Alternately, you may choose to provide definitions for 'fmap',\n'extract', and 'duplicate' satisfying these laws:\n\n@\n'extract' . 'duplicate'      = 'id'\n'fmap' 'extract' . 'duplicate' = 'id'\n'duplicate' . 'duplicate'    = 'fmap' 'duplicate' . 'duplicate'\n@\n\nIn this case you may not rely on the ability to define 'fmap' in\nterms of 'liftW'.\n\nYou may of course, choose to define both 'duplicate' /and/ 'extend'.\nIn that case you must also satisfy these laws:\n\n@\n'extend' f  = 'fmap' f . 'duplicate'\n'duplicate' = 'extend' id\n'fmap' f    = 'extend' (f . 'extract')\n@\n\nThese are the default definitions of 'extend' and 'duplicate' and\nthe definition of 'liftW' respectively.\n\n-}\n\nclass Functor w => Comonad w where\n  -- |\n  -- @\n  -- 'extract' . 'fmap' f = f . 'extract'\n  -- @\n  extract :: w a -> a\n\n  -- |\n  -- @\n  -- 'duplicate' = 'extend' 'id'\n  -- 'fmap' ('fmap' f) . 'duplicate' = 'duplicate' . 'fmap' f\n  -- @\n  duplicate :: w a -> w (w a)\n  duplicate = extend id\n\n  -- |\n  -- @\n  -- 'extend' f = 'fmap' f . 'duplicate'\n  -- @\n  extend :: (w a -> b) -> w a -> w b\n  extend f = fmap f . duplicate\n\n-- | A 'Profunctor' @p@ is a 'Sieve' __on__ @f@ if it is a subprofunctor of @'Star' f@.\n--\n-- That is to say it is a subset of @Hom(-,f=)@ closed under 'lmap' and 'rmap'.\n--\n-- Alternately, you can view it as a sieve __in__ the comma category @Hask/f@.\nclass (Profunctor p, Functor f) => Sieve p f | p -> f where\n  sieve :: p a b -> a -> f b\n\ninstance Sieve (->) Identity where\n  sieve f = Identity . f\n  {-# INLINE sieve #-}\n\ninstance (Monad m, Functor m) => Sieve (Arrow.Kleisli m) m where\n  sieve = Arrow.runKleisli\n  {-# INLINE sieve #-}\n\n-- | A 'Profunctor' @p@ is a 'Cosieve' __on__ @f@ if it is a subprofunctor of @'Costar' f@.\n--\n-- That is to say it is a subset of @Hom(f-,=)@ closed under 'lmap' and 'rmap'.\n--\n-- Alternately, you can view it as a cosieve __in__ the comma category @f/Hask@.\nclass (Profunctor p, Functor f) => Cosieve p f | p -> f where\n  cosieve :: p a b -> f a -> b\n\ninstance Cosieve (->) Identity where\n  cosieve f (Identity d) = f d\n  {-# INLINE cosieve #-}\n\ninstance Cosieve Tagged Proxy where\n  cosieve (Tagged a) _ = a\n  {-# INLINE cosieve #-}\n\n-- * Representable Profunctors\n\n-- | A 'Profunctor' @p@ is 'Representable' if there exists a 'Functor' @f@ such that\n-- @p d c@ is isomorphic to @d -> f c@.\nclass (Sieve p (Rep p), Strong p) => Representable p where\n  type Rep p :: * -> *\n  -- | Laws:\n  --\n  -- @\n  -- 'tabulate' '.' 'sieve' \u2261 'id'\n  -- 'sieve' '.' 'tabulate' \u2261 'id'\n  -- @\n  tabulate :: (d -> Rep p c) -> p d c\n\n-- | Default definition for 'first'' given that p is 'Representable'.\nfirstRep :: Representable p => p a b -> p (a, c) (b, c)\nfirstRep p = tabulate $ \\(a,c) -> (\\b -> (b, c)) <$> sieve p a\n\n-- | Default definition for 'second'' given that p is 'Representable'.\nsecondRep :: Representable p => p a b -> p (c, a) (c, b)\nsecondRep p = tabulate $ \\(c,a) -> (,) c <$> sieve p a\n\ninstance Representable (->) where\n  type Rep (->) = Identity\n  tabulate f = runIdentity . f\n  {-# INLINE tabulate #-}\n\ninstance (Monad m, Functor m) => Representable (Arrow.Kleisli m) where\n  type Rep (Arrow.Kleisli m) = m\n  tabulate = Arrow.Kleisli\n  {-# INLINE tabulate #-}\n\n{- TODO: coproducts and products\ninstance (Representable p, Representable q) => Representable (Bifunctor.Product p q)\n  type Rep (Bifunctor.Product p q) = Functor.Product p q\n\ninstance (Corepresentable p, Corepresentable q) => Corepresentable (Bifunctor.Product p q) where\n  type Rep (Bifunctor.Product p q) = Functor.Sum p q\n-}\n\n----------------------------------------------------------------------------\n-- * Pastro\n----------------------------------------------------------------------------\n\n-- | Pastro -| Tambara\n--\n-- @\n-- Pastro p ~ exists z. Costar ((,)z) `Procompose` p `Procompose` Star ((,)z)\n-- @\n--\n-- 'Pastro' freely makes any 'Profunctor' 'Strong'.\ndata Pastro p a b where\n  Pastro :: ((y, z) -> b) -> p x y -> (a -> (x, z)) -> Pastro p a b\n\ninstance Functor (Pastro p a) where\n  fmap f (Pastro l m r) = Pastro (f . l) m r\n\ninstance Profunctor (Pastro p) where\n  dimap f g (Pastro l m r) = Pastro (g . l) m (r . f)\n  lmap f (Pastro l m r) = Pastro l m (r . f)\n  rmap g (Pastro l m r) = Pastro (g . l) m r\n  w #. Pastro l m r = Pastro (w #. l) m r\n  Pastro l m r .# w = Pastro l m (r .# w)\n\n--------------------------------------------------------------------------------\n-- * Costrength for (,)\n--------------------------------------------------------------------------------\n\n-- | Analogous to 'ArrowLoop', 'loop' = 'unfirst'\nclass Profunctor p => Costrong p where\n  -- | Laws:\n  --\n  -- @\n  -- 'unfirst' \u2261 'unsecond' '.' 'dimap' 'swap' 'swap'\n  -- 'lmap' (,()) \u2261 'unfirst' '.' 'rmap' (,())\n  -- 'unfirst' '.' 'lmap' ('second' f) \u2261 'unfirst' '.' 'rmap' ('second' f)\n  -- 'unfirst' '.' 'unfirst' = 'unfirst' '.' 'dimap' assoc unassoc where\n  --   assoc ((a,b),c) = (a,(b,c))\n  --   unassoc (a,(b,c)) = ((a,b),c)\n  -- @\n  unfirst  :: p (a, d) (b, d) -> p a b\n  unfirst = unsecond . dimap swap swap\n\n  -- | Laws:\n  --\n  -- @\n  -- 'unsecond' \u2261 'unfirst' '.' 'dimap' 'swap' 'swap'\n  -- 'lmap' ((),) \u2261 'unsecond' '.' 'rmap' ((),)\n  -- 'unsecond' '.' 'lmap' ('first' f) \u2261 'unsecond' '.' 'rmap' ('first' f)\n  -- 'unsecond' '.' 'unsecond' = 'unsecond' '.' 'dimap' unassoc assoc where\n  --   assoc ((a,b),c) = (a,(b,c))\n  --   unassoc (a,(b,c)) = ((a,b),c)\n  -- @\n  unsecond :: p (d, a) (d, b) -> p a b\n  unsecond = unfirst . dimap swap swap\n\n  {-# MINIMAL unfirst | unsecond #-}\n\ninstance Costrong (->) where\n  unfirst f a = b where (b, d) = f (a, d)\n  unsecond f a = b where (d, b) = f (d, a)\n\ninstance Costrong Tagged where\n  unfirst (Tagged bd) = Tagged (fst bd)\n  unsecond (Tagged db) = Tagged (snd db)\n\ninstance MonadFix m => Costrong (Arrow.Kleisli m) where\n  unfirst (Arrow.Kleisli f) = Arrow.Kleisli (liftM fst . mfix . f')\n    where f' x y = f (x, snd y)\n\n-- | 'tabulate' and 'sieve' form two halves of an isomorphism.\n--\n-- This can be used with the combinators from the @lens@ package.\n--\n-- @'tabulated' :: 'Representable' p => 'Iso'' (d -> 'Rep' p c) (p d c)@\ntabulated :: (Representable p, Representable q) => Iso (d -> Rep p c) (d' -> Rep q c') (p d c) (q d' c')\ntabulated = dimap tabulate (fmap sieve)\n{-# INLINE tabulated #-}\n\n-- * Corepresentable Profunctors\n\n-- | A 'Profunctor' @p@ is 'Corepresentable' if there exists a 'Functor' @f@ such that\n-- @p d c@ is isomorphic to @f d -> c@.\nclass (Cosieve p (Corep p), Costrong p) => Corepresentable p where\n  type Corep p :: * -> *\n  -- | Laws:\n  --\n  -- @\n  -- 'cotabulate' '.' 'cosieve' \u2261 'id'\n  -- 'cosieve' '.' 'cotabulate' \u2261 'id'\n  -- @\n  cotabulate :: (Corep p d -> c) -> p d c\n\n-- | Default definition for 'unfirst' given that @p@ is 'Corepresentable'.\nunfirstCorep :: Corepresentable p => p (a, d) (b, d) -> p a b\nunfirstCorep p = cotabulate f\n  where f fa = b where (b, d) = cosieve p ((\\a -> (a, d)) <$> fa)\n\n-- | Default definition for 'unsecond' given that @p@ is 'Corepresentable'.\nunsecondCorep :: Corepresentable p => p (d, a) (d, b) -> p a b\nunsecondCorep p = cotabulate f\n  where f fa = b where (d, b) = cosieve p ((,) d <$> fa)\n\n-- | Default definition for 'closed' given that @p@ is 'Corepresentable'\nclosedCorep :: Corepresentable p => p a b -> p (x -> a) (x -> b)\nclosedCorep p = cotabulate $ \\fs x -> cosieve p (fmap ($ x) fs)\n\ninstance Corepresentable (->) where\n  type Corep (->) = Identity\n  cotabulate f = f . Identity\n  {-# INLINE cotabulate #-}\n\ninstance Corepresentable Tagged where\n  type Corep Tagged = Proxy\n  cotabulate f = Tagged (f Proxy)\n  {-# INLINE cotabulate #-}\n\n-- | 'cotabulate' and 'cosieve' form two halves of an isomorphism.\n--\n-- This can be used with the combinators from the @lens@ package.\n--\n-- @'cotabulated' :: 'Corep' f p => 'Iso'' (f d -> c) (p d c)@\ncotabulated :: (Corepresentable p, Corepresentable q) => Iso (Corep p d -> c) (Corep q d' -> c') (p d c) (q d' c')\ncotabulated = dimap cotabulate (fmap cosieve)\n{-# INLINE cotabulated #-}\n\n--------------------------------------------------------------------------------\n-- * Prep\n--------------------------------------------------------------------------------\n\n-- | @'Prep' -| 'Star' :: [Hask, Hask] -> Prof@\n--\n-- This gives rise to a monad in @Prof@, @('Star'.'Prep')@, and\n-- a comonad in @[Hask,Hask]@ @('Prep'.'Star')@\n--\n-- 'Prep' has a polymorphic kind since @5.6@.\n\n-- Prep :: (Type -> k -> Type) -> (k -> Type)\ndata Prep p a where\n  Prep :: x -> p x a -> Prep p a\n\ninstance Profunctor p => Functor (Prep p) where\n  fmap f (Prep x p) = Prep x (rmap f p)\n\ninstance (Applicative (Rep p), Representable p) => Applicative (Prep p) where\n  pure a = Prep () $ tabulate $ const $ pure a\n  Prep xf pf <*> Prep xa pa = Prep (xf,xa) (tabulate go) where\n    go (xf',xa') = sieve pf xf' <*> sieve pa xa'\n\ninstance (Monad (Rep p), Representable p) => Monad (Prep p) where\n  return a = Prep () $ tabulate $ const $ return a\n  Prep xa pa >>= f = Prep xa $ tabulate $ sieve pa >=> \\a -> case f a of\n    Prep xb pb -> sieve pb xb\n\n--------------------------------------------------------------------------------\n-- * Coprep\n--------------------------------------------------------------------------------\n\n-- | 'Prep' has a polymorphic kind since @5.6@.\n\n-- Coprep :: (k -> Type -> Type) -> (k -> Type)\nnewtype Coprep p a = Coprep { runCoprep :: forall r. p a r -> r }\n\ninstance Profunctor p => Functor (Coprep p) where\n  fmap f (Coprep g) = Coprep (g . lmap f)\n\n\n------------------------------------------------------------------------------\n-- Strong\n------------------------------------------------------------------------------\n\n-- | Generalizing 'Star' of a strong 'Functor'\n--\n-- /Note:/ Every 'Functor' in Haskell is strong with respect to @(,)@.\n--\n-- This describes profunctor strength with respect to the product structure\n-- of Hask.\n--\n-- <http://www.riec.tohoku.ac.jp/~asada/papers/arrStrMnd.pdf>\n--\nclass Profunctor p => Strong p where\n  -- | Laws:\n  --\n  -- @\n  -- 'first'' \u2261 'dimap' 'swap' 'swap' '.' 'second''\n  -- 'lmap' 'fst' \u2261 'rmap' 'fst' '.' 'first''\n  -- 'lmap' ('second'' f) '.' 'first'' \u2261 'rmap' ('second'' f) '.' 'first''\n  -- 'first'' '.' 'first'' \u2261 'dimap' assoc unassoc '.' 'first'' where\n  --   assoc ((a,b),c) = (a,(b,c))\n  --   unassoc (a,(b,c)) = ((a,b),c)\n  -- @\n  first' :: p a b  -> p (a, c) (b, c)\n  first' = dimap swap swap . second'\n\n  -- | Laws:\n  --\n  -- @\n  -- 'second'' \u2261 'dimap' 'swap' 'swap' '.' 'first''\n  -- 'lmap' 'snd' \u2261 'rmap' 'snd' '.' 'second''\n  -- 'lmap' ('first'' f) '.' 'second'' \u2261 'rmap' ('first'' f) '.' 'second''\n  -- 'second'' '.' 'second'' \u2261 'dimap' unassoc assoc '.' 'second'' where\n  --   assoc ((a,b),c) = (a,(b,c))\n  --   unassoc (a,(b,c)) = ((a,b),c)\n  -- @\n  second' :: p a b -> p (c, a) (c, b)\n  second' = dimap swap swap . first'\n\n  {-# MINIMAL first' | second' #-}\n\nuncurry' :: Strong p => p a (b -> c) -> p (a, b) c\nuncurry' = rmap (\\(f,x) -> f x) . first'\n{-# INLINE uncurry' #-}\n\nstrong :: Strong p => (a -> b -> c) -> p a b -> p a c\nstrong f x = dimap (\\a -> (a, a)) (\\(b, a) -> f a b) (first' x)\n\ninstance Strong (->) where\n  first' ab ~(a, c) = (ab a, c)\n  {-# INLINE first' #-}\n  second' ab ~(c, a) = (c, ab a)\n  {-# INLINE second' #-}\n\ninstance Monad m => Strong (Arrow.Kleisli m) where\n  first' (Arrow.Kleisli f) = Arrow.Kleisli $ \\ ~(a, c) -> do\n     b <- f a\n     return (b, c)\n  {-# INLINE first' #-}\n  second' (Arrow.Kleisli f) = Arrow.Kleisli $ \\ ~(c, a) -> do\n     b <- f a\n     return (c, b)\n  {-# INLINE second' #-}\n\n-- | A @'Tagged' s b@ value is a value @b@ with an attached phantom type @s@.\n-- This can be used in place of the more traditional but less safe idiom of\n-- passing in an undefined value with the type, because unlike an @(s -> b)@,\n-- a @'Tagged' s b@ can't try to use the argument @s@ as a real value.\n--\n-- Moreover, you don't have to rely on the compiler to inline away the extra\n-- argument, because the newtype is \\\"free\\\"\n--\n-- 'Tagged' has kind @k -> * -> *@ if the compiler supports @PolyKinds@, therefore\n-- there is an extra @k@ showing in the instance haddocks that may cause confusion.\nnewtype Tagged s b = Tagged { unTagged :: b } deriving\n  ( Eq, Ord, Ix, Bounded\n  , Generics.Generic\n  , Generics.Generic1\n  , Typeable\n  )\n\n-----------------------------------------------------------------------------\n-- Settable\n-----------------------------------------------------------------------------\n\n-- | Anything 'Settable' must be isomorphic to the 'Identity' 'Functor'.\nclass (Applicative f, Distributive f, Traversable f) => Settable f where\n  untainted :: f a -> a\n\n  untaintedDot :: Profunctor p => p a (f b) -> p a b\n  untaintedDot g = g `seq` rmap untainted g\n  {-# INLINE untaintedDot #-}\n\n  taintedDot :: Profunctor p => p a b -> p a (f b)\n  taintedDot g = g `seq` rmap pure g\n  {-# INLINE taintedDot #-}\n\n-- | So you can pass our 'Control.Lens.Setter.Setter' into combinators from other lens libraries.\ninstance Settable Identity where\n  untainted = runIdentity\n  {-# INLINE untainted #-}\n  untaintedDot = (runIdentity #.)\n  {-# INLINE untaintedDot #-}\n  taintedDot = (Identity #.)\n  {-# INLINE taintedDot #-}\n\n-- | 'Control.Lens.Fold.backwards'\ninstance Settable f => Settable (Backwards f) where\n  untainted = untaintedDot forwards\n  {-# INLINE untainted #-}\n\ninstance (Settable f, Settable g) => Settable (Compose f g) where\n  untainted = untaintedDot (untaintedDot getCompose)\n  {-# INLINE untainted #-}\n\n\n-- $setup\n-- >>> :set -XNoOverloadedStrings\n-- >>> import Control.Lens\n-- >>> import Control.Lens.Extras (is)\n-- >>> import Data.Function\n-- >>> import Data.List.Lens\n-- >>> import Data.List.NonEmpty (NonEmpty (..))\n-- >>> import Debug.SimpleReflect.Expr\n-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)\n-- >>> import Control.DeepSeq (NFData (..), force)\n-- >>> import Control.Exception (evaluate)\n-- >>> import Data.Maybe (fromMaybe)\n-- >>> import Data.Monoid (Sum (..))\n-- >>> import System.Timeout (timeout)\n-- >>> import qualified Data.Map as Map\n-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f\n-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g\n-- >>> let timingOut :: NFData a => a -> IO a; timingOut = fmap (fromMaybe (error \"timeout\")) . timeout (5*10^6) . evaluate . force\n\ninfixl 8 ^.., ^?, ^?!, ^@.., ^@?, ^@?!\n\ninfixl 8 ^., ^@.\n\ninfixl 4 <.>, <., .>\n\nclass Distributive f\n\n-- | The generalization of 'Costar' of 'Functor' that is strong with respect\n-- to 'Either'.\n--\n-- Note: This is also a notion of strength, except with regards to another monoidal\n-- structure that we can choose to equip Hask with: the cocartesian coproduct.\nclass Profunctor p => Choice p where\n  -- | Laws:\n  --\n  -- @\n  -- 'left'' \u2261 'dimap' swapE swapE '.' 'right'' where\n  --   swapE :: 'Either' a b -> 'Either' b a\n  --   swapE = 'either' 'Right' 'Left'\n  -- 'rmap' 'Left' \u2261 'lmap' 'Left' '.' 'left''\n  -- 'lmap' ('right' f) '.' 'left'' \u2261 'rmap' ('right' f) '.' 'left''\n  -- 'left'' '.' 'left'' \u2261 'dimap' assocE unassocE '.' 'left'' where\n  --   assocE :: 'Either' ('Either' a b) c -> 'Either' a ('Either' b c)\n  --   assocE ('Left' ('Left' a)) = 'Left' a\n  --   assocE ('Left' ('Right' b)) = 'Right' ('Left' b)\n  --   assocE ('Right' c) = 'Right' ('Right' c)\n  --   unassocE :: 'Either' a ('Either' b c) -> 'Either' ('Either' a b) c\n  --   unassocE ('Left' a) = 'Left' ('Left' a)\n  --   unassocE ('Right' ('Left' b)) = 'Left' ('Right' b)\n  --   unassocE ('Right' ('Right' c)) = 'Right' c\n  -- @\n  left'  :: p a b -> p (Either a c) (Either b c)\n  left' =  dimap (either Right Left) (either Right Left) . right'\n\n  -- | Laws:\n  --\n  -- @\n  -- 'right'' \u2261 'dimap' swapE swapE '.' 'left'' where\n  --   swapE :: 'Either' a b -> 'Either' b a\n  --   swapE = 'either' 'Right' 'Left'\n  -- 'rmap' 'Right' \u2261 'lmap' 'Right' '.' 'right''\n  -- 'lmap' ('left' f) '.' 'right'' \u2261 'rmap' ('left' f) '.' 'right''\n  -- 'right'' '.' 'right'' \u2261 'dimap' unassocE assocE '.' 'right'' where\n  --   assocE :: 'Either' ('Either' a b) c -> 'Either' a ('Either' b c)\n  --   assocE ('Left' ('Left' a)) = 'Left' a\n  --   assocE ('Left' ('Right' b)) = 'Right' ('Left' b)\n  --   assocE ('Right' c) = 'Right' ('Right' c)\n  --   unassocE :: 'Either' a ('Either' b c) -> 'Either' ('Either' a b) c\n  --   unassocE ('Left' a) = 'Left' ('Left' a)\n  --   unassocE ('Right' ('Left' b)) = 'Left' ('Right' b)\n  --   unassocE ('Right' ('Right' c)) = 'Right' c\n  -- @\n  right' :: p a b -> p (Either c a) (Either c b)\n  right' =  dimap (either Right Left) (either Right Left) . left'\n\n  {-# MINIMAL left' | right' #-}\n\ninstance Choice (->) where\n  left' ab (Left a) = Left (ab a)\n  left' _ (Right c) = Right c\n  {-# INLINE left' #-}\n  right' = fmap\n  {-# INLINE right' #-}\n\ninstance Profunctor (->) where\n  dimap ab cd bc = cd . bc . ab\n  {-# INLINE dimap #-}\n  lmap = flip (.)\n  {-# INLINE lmap #-}\n  rmap = (.)\n  {-# INLINE rmap #-}\n  (#.) _ = coerce (\\x -> x :: b) :: forall a b. Coercible b a => a -> b\n  (.#) pbc _ = coerce pbc\n  {-# INLINE (#.) #-}\n  {-# INLINE (.#) #-}\n\ninstance Comonad Identity\ninstance Comonad ((,) i)\ninstance Applicative (Tagged a)\ninstance Functor (Tagged a)\ninstance Profunctor Tagged\ninstance Profunctor (Arrow.Kleisli m)\ninstance Distributive (Compose f g)\ninstance Distributive (Backwards f)\ninstance Distributive Identity\n\ninstance Monad m => Choice (Arrow.Kleisli m) where\n  left' = left\n  {-# INLINE left' #-}\n  right' = right\n  {-# INLINE right' #-}\n\ninstance Choice Tagged where\n  left' (Tagged b) = Tagged (Left b)\n  {-# INLINE left' #-}\n  right' (Tagged b) = Tagged (Right b)\n  {-# INLINE right' #-}\n\n-- | A strong lax semi-monoidal endofunctor.\n-- This is equivalent to an 'Applicative' without 'pure'.\n--\n-- Laws:\n--\n-- @\n-- ('.') '<$>' u '<.>' v '<.>' w = u '<.>' (v '<.>' w)\n-- x '<.>' (f '<$>' y) = ('.' f) '<$>' x '<.>' y\n-- f '<$>' (x '<.>' y) = (f '.') '<$>' x '<.>' y\n-- @\n--\n-- The laws imply that `.>` and `<.` really ignore their\n-- left and right results, respectively, and really\n-- return their right and left results, respectively.\n-- Specifically,\n--\n-- @\n-- (mf '<$>' m) '.>' (nf '<$>' n) = nf '<$>' (m '.>' n)\n-- (mf '<$>' m) '<.' (nf '<$>' n) = mf '<$>' (m '<.' n)\n-- @\nclass Functor f => Apply f where\n  (<.>) :: f (a -> b) -> f a -> f b\n  (<.>) = liftF2 id\n\n  -- | @ a '.>' b = 'const' 'id' '<$>' a '<.>' b @\n  (.>) :: f a -> f b -> f b\n  a .> b = const id <$> a <.> b\n\n  -- | @ a '<.' b = 'const' '<$>' a '<.>' b @\n  (<.) :: f a -> f b -> f a\n  a <. b = const <$> a <.> b\n\n  -- | Lift a binary function into a comonad with zipping\n  liftF2 :: (a -> b -> c) -> f a -> f b -> f c\n  liftF2 f a b = f <$> a <.> b\n  {-# INLINE liftF2 #-}\n\ninstance Apply (Tagged a) where\n  (<.>) = (<*>)\n  (<.) = (<*)\n  (.>) = (*>)\n\ninstance Apply Proxy where\n  (<.>) = (<*>)\n  (<.) = (<*)\n  (.>) = (*>)\n\ninstance Apply f => Apply (Backwards f) where\n  Backwards f <.> Backwards a = Backwards (flip id <$> a <.> f)\n\ninstance (Apply f, Apply g) => Apply (Compose f g) where\n  Compose f <.> Compose x = Compose ((<.>) <$> f <.> x)\n\ninstance (Apply f, Apply g) => Apply (Functor.Product f g) where\n  Functor.Pair f g <.> Functor.Pair x y = Functor.Pair (f <.> x) (g <.> y)\n\n-- | A @'(,)' m@ is not 'Applicative' unless its @m@ is a 'Monoid', but it is an instance of 'Apply'\ninstance Semigroup m => Apply ((,)m) where\n  (m, f) <.> (n, a) = (m <> n, f a)\n  (m, a) <.  (n, _) = (m <> n, a)\n  (m, _)  .> (n, b) = (m <> n, b)\n\ninstance Apply NonEmpty where\n  (<.>) = ap\n\ninstance Apply (Either a) where\n  Left a  <.> _       = Left a\n  Right _ <.> Left a  = Left a\n  Right f <.> Right b = Right (f b)\n\n  Left a  <.  _       = Left a\n  Right _ <.  Left a  = Left a\n  Right a <.  Right _ = Right a\n\n  Left a   .> _       = Left a\n  Right _  .> Left a  = Left a\n  Right _  .> Right b = Right b\n\n-- | A @'Const' m@ is not 'Applicative' unless its @m@ is a 'Monoid', but it is an instance of 'Apply'\ninstance Semigroup m => Apply (Const m) where\n  Const m <.> Const n = Const (m <> n)\n  Const m <.  Const n = Const (m <> n)\n  Const m  .> Const n = Const (m <> n)\n\ninstance Apply ((->)m) where\n  (<.>) = (<*>)\n  (<. ) = (<* )\n  ( .>) = ( *>)\n\ninstance Apply ZipList where\n  (<.>) = (<*>)\n  (<. ) = (<* )\n  ( .>) = ( *>)\n\ninstance Apply [] where\n  (<.>) = (<*>)\n  (<. ) = (<* )\n  ( .>) = ( *>)\n\ninstance Apply IO where\n  (<.>) = (<*>)\n  (<. ) = (<* )\n  ( .>) = ( *>)\n\ninstance Apply Maybe where\n  (<.>) = (<*>)\n  (<. ) = (<* )\n  ( .>) = ( *>)\n\ninstance Apply Identity where\n  (<.>) = (<*>)\n  (<. ) = (<* )\n  ( .>) = ( *>)\n\ninstance Apply w => Apply (IdentityT w) where\n  IdentityT wa <.> IdentityT wb = IdentityT (wa <.> wb)\n\ninstance Monad m => Apply (WrappedMonad m) where\n  (<.>) = (<*>)\n  (<. ) = (<* )\n  ( .>) = ( *>)\n\ninstance Arrow a => Apply (WrappedArrow a b) where\n  (<.>) = (<*>)\n  (<. ) = (<* )\n  ( .>) = ( *>)\n\ninstance Apply Complex where\n  (a :+ b) <.> (c :+ d) = a c :+ b d\n\n-- | A 'Map k' is not 'Applicative', but it is an instance of 'Apply'\ninstance Ord k => Apply (Map k) where\n  (<.>) = Map.intersectionWith id\n  (<. ) = Map.intersectionWith const\n  ( .>) = Map.intersectionWith (const id)\n\n-- | An 'IntMap' is not 'Applicative', but it is an instance of 'Apply'\ninstance Apply IntMap.IntMap where\n  (<.>) = IntMap.intersectionWith id\n  (<. ) = IntMap.intersectionWith const\n  ( .>) = IntMap.intersectionWith (const id)\n\ninstance Apply Tree where\n  (<.>) = (<*>)\n  (<. ) = (<* )\n  ( .>) = ( *>)\n\n-- MaybeT is _not_ the same as Compose f Maybe\ninstance (Functor m, Monad m) => Apply (MaybeT m) where\n  (<.>) = apDefault\n\ninstance (Functor m, Monad m) => Apply (ExceptT e m) where\n  (<.>) = apDefault\n\ninstance Apply m => Apply (ReaderT e m) where\n  ReaderT f <.> ReaderT a = ReaderT $ \\e -> f e <.> a e\n\n-- unfortunately, WriterT has its wrapped product in the wrong order to just use (<.>) instead of flap\n-- | A @'Strict.WriterT' w m@ is not 'Applicative' unless its @w@ is a 'Monoid', but it is an instance of 'Apply'\ninstance (Apply m, Semigroup w) => Apply (Strict.WriterT w m) where\n  Strict.WriterT f <.> Strict.WriterT a = Strict.WriterT $ flap <$> f <.> a where\n    flap (x,m) (y,n) = (x y, m <> n)\n\n-- | A @'Lazy.WriterT' w m@ is not 'Applicative' unless its @w@ is a 'Monoid', but it is an instance of 'Apply'\ninstance (Apply m, Semigroup w) => Apply (Lazy.WriterT w m) where\n  Lazy.WriterT f <.> Lazy.WriterT a = Lazy.WriterT $ flap <$> f <.> a where\n    flap ~(x,m) ~(y,n) = (x y, m <> n)\n\ninstance Apply (ContT r m) where\n  ContT f <.> ContT v = ContT $ \\k -> f $ \\g -> v (k . g)\n\n-- | Wrap an 'Applicative' to be used as a member of 'Apply'\nnewtype WrappedApplicative f a = WrapApplicative { unwrapApplicative :: f a }\n\ninstance Functor f => Functor (WrappedApplicative f) where\n  fmap f (WrapApplicative a) = WrapApplicative (f <$> a)\n\ninstance Applicative f => Apply (WrappedApplicative f) where\n  WrapApplicative f <.> WrapApplicative a = WrapApplicative (f <*> a)\n  WrapApplicative a <.  WrapApplicative b = WrapApplicative (a <*  b)\n  WrapApplicative a  .> WrapApplicative b = WrapApplicative (a  *> b)\n\ninstance Applicative f => Applicative (WrappedApplicative f) where\n  pure = WrapApplicative . pure\n  WrapApplicative f <*> WrapApplicative a = WrapApplicative (f <*> a)\n  WrapApplicative a <*  WrapApplicative b = WrapApplicative (a <*  b)\n  WrapApplicative a  *> WrapApplicative b = WrapApplicative (a  *> b)\n\ninstance Alternative f => Alternative (WrappedApplicative f) where\n  empty = WrapApplicative empty\n  WrapApplicative a <|> WrapApplicative b = WrapApplicative (a <|> b)\n\n-- | Transform an Apply into an Applicative by adding a unit.\nnewtype MaybeApply f a = MaybeApply { runMaybeApply :: Either (f a) a }\n\n-- | Apply a non-empty container of functions to a possibly-empty-with-unit container of values.\n(<.*>) :: (Apply f) => f (a -> b) -> MaybeApply f a -> f b\nff <.*> MaybeApply (Left fa) = ff <.> fa\nff <.*> MaybeApply (Right a) = ($ a) <$> ff\ninfixl 4 <.*>\n\n-- | Apply a possibly-empty-with-unit container of functions to a non-empty container of values.\n(<*.>) :: (Apply f) => MaybeApply f (a -> b) -> f a -> f b\nMaybeApply (Left ff) <*.> fa = ff <.> fa\nMaybeApply (Right f) <*.> fa = f <$> fa\ninfixl 4 <*.>\n\n-- | Traverse a 'Traversable' using 'Apply', getting the results back in a 'MaybeApply'.\ntraverse1Maybe :: (Traversable t, Apply f) => (a -> f b) -> t a -> MaybeApply f (t b)\ntraverse1Maybe f = traverse (MaybeApply . Left . f)\n\ninstance Functor f => Functor (MaybeApply f) where\n  fmap f (MaybeApply (Right a)) = MaybeApply (Right (f     a ))\n  fmap f (MaybeApply (Left fa)) = MaybeApply (Left  (f <$> fa))\n\ninstance Apply f => Apply (MaybeApply f) where\n  MaybeApply (Right f) <.> MaybeApply (Right a) = MaybeApply (Right (f         a ))\n  MaybeApply (Right f) <.> MaybeApply (Left fa) = MaybeApply (Left  (f     <$> fa))\n  MaybeApply (Left ff) <.> MaybeApply (Right a) = MaybeApply (Left  (($ a) <$> ff))\n  MaybeApply (Left ff) <.> MaybeApply (Left fa) = MaybeApply (Left  (ff    <.> fa))\n\n  MaybeApply a         <. MaybeApply (Right _) = MaybeApply a\n  MaybeApply (Right a) <. MaybeApply (Left fb) = MaybeApply (Left (a  <$ fb))\n  MaybeApply (Left fa) <. MaybeApply (Left fb) = MaybeApply (Left (fa <. fb))\n\n  MaybeApply (Right _) .> MaybeApply b = MaybeApply b\n  MaybeApply (Left fa) .> MaybeApply (Right b) = MaybeApply (Left (fa $> b ))\n  MaybeApply (Left fa) .> MaybeApply (Left fb) = MaybeApply (Left (fa .> fb))\n\ninstance Apply f => Applicative (MaybeApply f) where\n  pure a = MaybeApply (Right a)\n  (<*>) = (<.>)\n  (<* ) = (<. )\n  ( *>) = ( .>)\n\ninstance Apply Down where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\n\ninstance Apply Monoid.Sum where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\ninstance Apply Monoid.Product where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\ninstance Apply Monoid.Dual where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\ninstance Apply Monoid.First where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\ninstance Apply Monoid.Last where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\nderiving instance Apply f => Apply (Monoid.Alt f)\n-- in GHC 8.6 we'll have to deal with Apply f => Apply (Ap f) the same way\ninstance Apply Semigroup.First where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\ninstance Apply Semigroup.Last where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\ninstance Apply Semigroup.Min where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\ninstance Apply Semigroup.Max where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\n\ninstance (Apply f, Apply g) => Apply (f :*: g) where\n  (a :*: b) <.> (c :*: d) = (a <.> c) :*: (b <.> d)\n\nderiving instance Apply f => Apply (M1 i t f)\nderiving instance Apply f => Apply (Rec1 f)\n\ninstance (Apply f, Apply g) => Apply (f :.: g) where\n  Comp1 m <.> Comp1 n = Comp1 $ (<.>) <$> m <.> n\n\ninstance Apply U1 where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\n\n-- | A @'K1' i c@ is not 'Applicative' unless its @c@ is a 'Monoid', but it is an instance of 'Apply'\ninstance Semigroup c => Apply (K1 i c) where\n  K1 a <.> K1 b = K1 (a <> b)\n  K1 a <.  K1 b = K1 (a <> b)\n  K1 a  .> K1 b = K1 (a <> b)\ninstance Apply Par1 where (<.>)=(<*>);(.>)=(*>);(<.)=(<*)\n\n-- | A 'V1' is not 'Applicative', but it is an instance of 'Apply'\ninstance Apply Generics.V1 where\n  e <.> _ = case e of {}\n------------------------------------------------------------------------------\n-- Magma\n------------------------------------------------------------------------------\n\n-- | This provides a way to peek at the internal structure of a\n-- 'Control.Lens.Traversal.Traversal' or 'Control.Lens.Traversal.IndexedTraversal'\ndata Magma i t b a where\n  MagmaAp   :: Magma i (x -> y) b a -> Magma i x b a -> Magma i y b a\n  MagmaPure :: x -> Magma i x b a\n  MagmaFmap :: (x -> y) -> Magma i x b a -> Magma i y b a\n  Magma :: i -> a -> Magma i b b a\n\n-- note the 3rd argument infers as phantom, but that would be unsound\ntype role Magma representational nominal nominal nominal\n\ninstance Functor (Magma i t b) where\n  fmap f (MagmaAp x y)    = MagmaAp (fmap f x) (fmap f y)\n  fmap _ (MagmaPure x)    = MagmaPure x\n  fmap f (MagmaFmap xy x) = MagmaFmap xy (fmap f x)\n  fmap f (Magma i a)  = Magma i (f a)\n\ninstance Foldable (Magma i t b) where\n  foldMap f (MagmaAp x y)   = foldMap f x `mappend` foldMap f y\n  foldMap _ MagmaPure{}     = mempty\n  foldMap f (MagmaFmap _ x) = foldMap f x\n  foldMap f (Magma _ a) = f a\n\ninstance Traversable (Magma i t b) where\n  traverse f (MagmaAp x y)    = MagmaAp <$> traverse f x <*> traverse f y\n  traverse _ (MagmaPure x)    = pure (MagmaPure x)\n  traverse f (MagmaFmap xy x) = MagmaFmap xy <$> traverse f x\n  traverse f (Magma i a)  = Magma i <$> f a\n\ninstance (Show i, Show a) => Show (Magma i t b a) where\n  showsPrec d (MagmaAp x y) = showParen (d > 4) $\n    showsPrec 4 x . showString \" <*> \" . showsPrec 5 y\n  showsPrec d (MagmaPure _) = showParen (d > 10) $\n    showString \"pure ..\"\n  showsPrec d (MagmaFmap _ x) = showParen (d > 4) $\n    showString \".. <$> \" . showsPrec 5 x\n  showsPrec d (Magma i a) = showParen (d > 10) $\n    showString \"Magma \" . showsPrec 11 i . showChar ' ' . showsPrec 11 a\n\n-- | Run a 'Magma' where all the individual leaves have been converted to the\n-- expected type\nrunMagma :: Magma i t a a -> t\nrunMagma (MagmaAp l r)   = runMagma l (runMagma r)\nrunMagma (MagmaFmap f r) = f (runMagma r)\nrunMagma (MagmaPure x)   = x\nrunMagma (Magma _ a) = a\n\n------------------------------------------------------------------------------\n-- Molten\n------------------------------------------------------------------------------\n\n-- | This is a a non-reassociating initially encoded version of 'Bazaar'.\nnewtype Molten i a b t = Molten { runMolten :: Magma i t b a }\n\ninstance Functor (Molten i a b) where\n  fmap f (Molten xs) = Molten (MagmaFmap f xs)\n  {-# INLINE fmap #-}\n\ninstance Apply (Molten i a b) where\n  (<.>) = (<*>)\n  {-# INLINE (<.>) #-}\n\ninstance Applicative (Molten i a b) where\n  pure  = Molten #. MagmaPure\n  {-# INLINE pure #-}\n  Molten xs <*> Molten ys = Molten (MagmaAp xs ys)\n  {-# INLINE (<*>) #-}\n\n------------------------------------------------------------------------------\n-- Mafic\n------------------------------------------------------------------------------\n\n-- | This is used to generate an indexed magma from an unindexed source\n--\n-- By constructing it this way we avoid infinite reassociations in sums where possible.\ndata Mafic a b t = Mafic Int (Int -> Magma Int t b a)\n\n-- | Generate a 'Magma' using from a prefix sum.\nrunMafic :: Mafic a b t -> Magma Int t b a\nrunMafic (Mafic _ k) = k 0\n\ninstance Functor (Mafic a b) where\n  fmap f (Mafic w k) = Mafic w (MagmaFmap f . k)\n  {-# INLINE fmap #-}\n\ninstance Apply (Mafic a b) where\n  Mafic wf mf <.> ~(Mafic wa ma) = Mafic (wf + wa) $ \\o -> MagmaAp (mf o) (ma (o + wf))\n  {-# INLINE (<.>) #-}\n\ninstance Applicative (Mafic a b) where\n  pure a = Mafic 0 $ \\_ -> MagmaPure a\n  {-# INLINE pure #-}\n  Mafic wf mf <*> ~(Mafic wa ma) = Mafic (wf + wa) $ \\o -> MagmaAp (mf o) (ma (o + wf))\n  {-# INLINE (<*>) #-}\n\n------------------------------------------------------------------------------\n-- TakingWhile\n------------------------------------------------------------------------------\n\n-- | This is used to generate an indexed magma from an unindexed source\n--\n-- By constructing it this way we avoid infinite reassociations where possible.\n--\n-- In @'TakingWhile' p g a b t@, @g@ has a @nominal@ role to avoid exposing an illegal _|_ via 'Contravariant',\n-- while the remaining arguments are degraded to a @nominal@ role by the invariants of 'Magma'\ndata TakingWhile p (g :: Type -> Type) a b t = TakingWhile Bool t (Bool -> Magma () t b (Corep p a))\ntype role TakingWhile nominal nominal nominal nominal nominal\n\n-- | Generate a 'Magma' with leaves only while the predicate holds from left to right.\nrunTakingWhile :: TakingWhile p f a b t -> Magma () t b (Corep p a)\nrunTakingWhile (TakingWhile _ _ k) = k True\n\ninstance Functor (TakingWhile p f a b) where\n  fmap f (TakingWhile w t k) = let ft = f t in TakingWhile w ft $ \\b -> if b then MagmaFmap f (k b) else MagmaPure ft\n  {-# INLINE fmap #-}\n\ninstance Apply (TakingWhile p f a b) where\n  TakingWhile wf tf mf <.> ~(TakingWhile wa ta ma) = TakingWhile (wf && wa) (tf ta) $ \\o ->\n    if o then MagmaAp (mf True) (ma wf) else MagmaPure (tf ta)\n  {-# INLINE (<.>) #-}\n\ninstance Applicative (TakingWhile p f a b) where\n  pure a = TakingWhile True a $ \\_ -> MagmaPure a\n  {-# INLINE pure #-}\n  TakingWhile wf tf mf <*> ~(TakingWhile wa ta ma) = TakingWhile (wf && wa) (tf ta) $ \\o ->\n    if o then MagmaAp (mf True) (ma wf) else MagmaPure (tf ta)\n  {-# INLINE (<*>) #-}\n\n\n\n-- This constraint is unused intentionally, it protects TakingWhile\ninstance Contravariant f => Contravariant (TakingWhile p f a b) where\n  contramap _ = (<$) (error \"contramap: TakingWhile\")\n  {-# INLINE contramap #-}\n\n------------------------------------------------------------------------------\n-- Folding\n------------------------------------------------------------------------------\n\n-- | A 'Monoid' for a 'Contravariant' 'Applicative'.\nnewtype Folding f a = Folding { getFolding :: f a }\n\ninstance (Contravariant f, Applicative f) => Semigroup (Folding f a) where\n  Folding fr <> Folding fs = Folding (fr *> fs)\n  {-# INLINE (<>) #-}\n\ninstance (Contravariant f, Applicative f) => Monoid (Folding f a) where\n  mempty = Folding noEffect\n  {-# INLINE mempty #-}\n\n------------------------------------------------------------------------------\n-- Traversed\n------------------------------------------------------------------------------\n\n-- | Used internally by 'Control.Lens.Traversal.traverseOf_' and the like.\n--\n-- The argument 'a' of the result should not be used!\nnewtype Traversed a f = Traversed { getTraversed :: f a }\n\n-- See 4.16 Changelog entry for the explanation of \"why not Apply f =>\"?\ninstance Applicative f => Semigroup (Traversed a f) where\n  Traversed ma <> Traversed mb = Traversed (ma *> mb)\n  {-# INLINE (<>) #-}\n\ninstance Applicative f => Monoid (Traversed a f) where\n  mempty = Traversed (pure (error \"Traversed: value used\"))\n  {-# INLINE mempty #-}\n\n------------------------------------------------------------------------------\n-- TraversedF\n------------------------------------------------------------------------------\n\n-- | Used internally by 'Control.Lens.Fold.traverse1Of_' and the like.\n--\n-- @since 4.16\nnewtype TraversedF a f = TraversedF { getTraversedF :: f a }\n\ninstance Apply f => Semigroup (TraversedF a f) where\n  TraversedF ma <> TraversedF mb = TraversedF (ma .> mb)\n  {-# INLINE (<>) #-}\n\ninstance (Apply f, Applicative f) => Monoid (TraversedF a f) where\n  mempty = TraversedF (pure (error \"TraversedF: value used\"))\n  {-# INLINE mempty #-}\n\n------------------------------------------------------------------------------\n-- Sequenced\n------------------------------------------------------------------------------\n\n-- | Used internally by 'Control.Lens.Traversal.mapM_' and the like.\n--\n-- The argument 'a' of the result should not be used!\n--\n-- See 4.16 Changelog entry for the explanation of \"why not Apply f =>\"?\nnewtype Sequenced a m = Sequenced { getSequenced :: m a }\n\ninstance Monad m => Semigroup (Sequenced a m) where\n  Sequenced ma <> Sequenced mb = Sequenced (ma >> mb)\n  {-# INLINE (<>) #-}\n\ninstance Monad m => Monoid (Sequenced a m) where\n  mempty = Sequenced (return (error \"Sequenced: value used\"))\n  {-# INLINE mempty #-}\n\n------------------------------------------------------------------------------\n-- NonEmptyDList\n------------------------------------------------------------------------------\n\nnewtype NonEmptyDList a\n  = NonEmptyDList { getNonEmptyDList :: [a] -> NonEmpty.NonEmpty a }\n\ninstance Semigroup (NonEmptyDList a) where\n  NonEmptyDList f <> NonEmptyDList g = NonEmptyDList (f . NonEmpty.toList . g)\n\n------------------------------------------------------------------------------\n-- Leftmost and Rightmost\n------------------------------------------------------------------------------\n\n-- | Used for 'Control.Lens.Fold.firstOf'.\ndata Leftmost a = LPure | LLeaf a | LStep (Leftmost a)\n\ninstance Semigroup (Leftmost a) where\n  x <> y = LStep $ case x of\n    LPure    -> y\n    LLeaf _  -> x\n    LStep x' -> case y of\n      -- The last two cases make firstOf produce a Just as soon as any element\n      -- is encountered, and possibly serve as a micro-optimisation; this\n      -- behaviour can be disabled by replacing them with _ -> x <> y'.\n      -- Note that this means that firstOf (backwards folded) [1..] is Just _|_.\n      LPure    -> x'\n      LLeaf a  -> LLeaf $ fromMaybe a (getLeftmost x')\n      LStep y' -> mappend x' y'\n\ninstance Monoid (Leftmost a) where\n  mempty = LPure\n  {-# INLINE mempty #-}\n\n-- | Extract the 'Leftmost' element. This will fairly eagerly determine that it can return 'Just'\n-- the moment it sees any element at all.\ngetLeftmost :: Leftmost a -> Maybe a\ngetLeftmost LPure = Nothing\ngetLeftmost (LLeaf a) = Just a\ngetLeftmost (LStep x) = getLeftmost x\n\n-- | Used for 'Control.Lens.Fold.lastOf'.\ndata Rightmost a = RPure | RLeaf a | RStep (Rightmost a)\n\ninstance Semigroup (Rightmost a) where\n  x <> y = RStep $ case y of\n    RPure    -> x\n    RLeaf _  -> y\n    RStep y' -> case x of\n      -- The last two cases make lastOf produce a Just as soon as any element\n      -- is encountered, and possibly serve as a micro-optimisation; this\n      -- behaviour can be disabled by replacing them with _ -> x <> y'.\n      -- Note that this means that lastOf folded [1..] is Just _|_.\n      RPure    -> y'\n      RLeaf a  -> RLeaf $ fromMaybe a (getRightmost y')\n      RStep x' -> mappend x' y'\n\ninstance Monoid (Rightmost a) where\n  mempty = RPure\n  {-# INLINE mempty #-}\n\n-- | Extract the 'Rightmost' element. This will fairly eagerly determine that it can return 'Just'\n-- the moment it sees any element at all.\ngetRightmost :: Rightmost a -> Maybe a\ngetRightmost RPure = Nothing\ngetRightmost (RLeaf a) = Just a\ngetRightmost (RStep x) = getRightmost x\n\n-------------------------------------------------------------------------------\n-- Getters\n-------------------------------------------------------------------------------\n\n-- | Build an (index-preserving) 'Getter' from an arbitrary Haskell function.\n--\n-- @\n-- 'to' f '.' 'to' g \u2261 'to' (g '.' f)\n-- @\n--\n-- @\n-- a '^.' 'to' f \u2261 f a\n-- @\n--\n-- >>> a ^.to f\n-- f a\n--\n-- >>> (\"hello\",\"world\")^.to snd\n-- \"world\"\n--\n-- >>> 5^.to succ\n-- 6\n--\n-- >>> (0, -5)^._2.to abs\n-- 5\n--\n-- @\n-- 'to' :: (s -> a) -> 'IndexPreservingGetter' s a\n-- @\nto :: (Profunctor p, Contravariant f) => (s -> a) -> Optic' p f s a\nto k = dimap k (contramap k)\n{-# INLINE to #-}\n\n-- |\n-- @\n-- 'ito' :: (s -> (i, a)) -> 'IndexedGetter' i s a\n-- @\nito :: (Indexable i p, Contravariant f) => (s -> (i, a)) -> Over' p f s a\nito k = dimap k (contramap (snd . k)) . uncurry . indexed\n{-# INLINE ito #-}\n\n\n-- | Build an constant-valued (index-preserving) 'Getter' from an arbitrary Haskell value.\n--\n-- @\n-- 'like' a '.' 'like' b \u2261 'like' b\n-- a '^.' 'like' b \u2261 b\n-- a '^.' 'like' b \u2261 a '^.' 'to' ('const' b)\n-- @\n--\n-- This can be useful as a second case 'failing' a 'Fold'\n-- e.g. @foo `failing` 'like' 0@\n--\n-- @\n-- 'like' :: a -> 'IndexPreservingGetter' s a\n-- @\nlike :: (Profunctor p, Contravariant f, Functor f) => a -> Optic' p f s a\nlike a = to (const a)\n{-# INLINE like #-}\n\n-- |\n-- @\n-- 'ilike' :: i -> a -> 'IndexedGetter' i s a\n-- @\nilike :: (Indexable i p, Contravariant f, Functor f) => i -> a -> Over' p f s a\nilike i a = ito (const (i, a))\n{-# INLINE ilike #-}\n\n-- | When you see this in a type signature it indicates that you can\n-- pass the function a 'Lens', 'Getter',\n-- 'Control.Lens.Traversal.Traversal', 'Control.Lens.Fold.Fold',\n-- 'Control.Lens.Prism.Prism', 'Control.Lens.Iso.Iso', or one of\n-- the indexed variants, and it will just \\\"do the right thing\\\".\n--\n-- Most 'Getter' combinators are able to be used with both a 'Getter' or a\n-- 'Control.Lens.Fold.Fold' in limited situations, to do so, they need to be\n-- monomorphic in what we are going to extract with 'Control.Applicative.Const'. To be compatible\n-- with 'Lens', 'Control.Lens.Traversal.Traversal' and\n-- 'Control.Lens.Iso.Iso' we also restricted choices of the irrelevant @t@ and\n-- @b@ parameters.\n--\n-- If a function accepts a @'Getting' r s a@, then when @r@ is a 'Data.Monoid.Monoid', then\n-- you can pass a 'Control.Lens.Fold.Fold' (or\n-- 'Control.Lens.Traversal.Traversal'), otherwise you can only pass this a\n-- 'Getter' or 'Lens'.\ntype Getting r s a = (a -> Const r a) -> s -> Const r s\n\n-- | Used to consume an 'Control.Lens.Fold.IndexedFold'.\ntype IndexedGetting i m s a = Indexed i a (Const m a) -> s -> Const m s\n\n-- | This is a convenient alias used when consuming (indexed) getters and (indexed) folds\n-- in a highly general fashion.\ntype Accessing p m s a = p a (Const m a) -> s -> Const m s\n\n-------------------------------------------------------------------------------\n-- Getting Values\n-------------------------------------------------------------------------------\n\n-- | View the value pointed to by a 'Getter', 'Control.Lens.Iso.Iso' or\n-- 'Lens' or the result of folding over all the results of a\n-- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that points\n-- at a monoidal value.\n--\n-- @\n-- 'view' '.' 'to' \u2261 'id'\n-- @\n--\n-- >>> view (to f) a\n-- f a\n--\n-- >>> view _2 (1,\"hello\")\n-- \"hello\"\n--\n-- >>> view (to succ) 5\n-- 6\n--\n-- >>> view (_2._1) (\"hello\",(\"world\",\"!!!\"))\n-- \"world\"\n--\n--\n-- As 'view' is commonly used to access the target of a 'Getter' or obtain a monoidal summary of the targets of a 'Fold',\n-- It may be useful to think of it as having one of these more restricted signatures:\n--\n-- @\n-- 'view' ::             'Getter' s a     -> s -> a\n-- 'view' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Fold.Fold' s m       -> s -> m\n-- 'view' ::             'Control.Lens.Iso.Iso'' s a       -> s -> a\n-- 'view' ::             'Lens'' s a      -> s -> a\n-- 'view' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Traversal.Traversal'' s m -> s -> m\n-- @\n--\n-- In a more general setting, such as when working with a 'Monad' transformer stack you can use:\n--\n-- @\n-- 'view' :: 'MonadReader' s m             => 'Getter' s a     -> m a\n-- 'view' :: ('MonadReader' s m, 'Data.Monoid.Monoid' a) => 'Control.Lens.Fold.Fold' s a       -> m a\n-- 'view' :: 'MonadReader' s m             => 'Control.Lens.Iso.Iso'' s a       -> m a\n-- 'view' :: 'MonadReader' s m             => 'Lens'' s a      -> m a\n-- 'view' :: ('MonadReader' s m, 'Data.Monoid.Monoid' a) => 'Control.Lens.Traversal.Traversal'' s a -> m a\n-- @\nview :: MonadReader s m => Getting a s a -> m a\nview l = Reader.asks (getConst #. l Const)\n{-# INLINE view #-}\n\n-- | View a function of the value pointed to by a 'Getter' or 'Lens' or the result of\n-- folding over the result of mapping the targets of a 'Control.Lens.Fold.Fold' or\n-- 'Control.Lens.Traversal.Traversal'.\n--\n-- @\n-- 'views' l f \u2261 'view' (l '.' 'to' f)\n-- @\n--\n-- >>> views (to f) g a\n-- g (f a)\n--\n-- >>> views _2 length (1,\"hello\")\n-- 5\n--\n-- As 'views' is commonly used to access the target of a 'Getter' or obtain a monoidal summary of the targets of a 'Fold',\n-- It may be useful to think of it as having one of these more restricted signatures:\n--\n-- @\n-- 'views' ::             'Getter' s a     -> (a -> r) -> s -> r\n-- 'views' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Fold.Fold' s a       -> (a -> m) -> s -> m\n-- 'views' ::             'Control.Lens.Iso.Iso'' s a       -> (a -> r) -> s -> r\n-- 'views' ::             'Lens'' s a      -> (a -> r) -> s -> r\n-- 'views' :: 'Data.Monoid.Monoid' m => 'Control.Lens.Traversal.Traversal'' s a -> (a -> m) -> s -> m\n-- @\n--\n-- In a more general setting, such as when working with a 'Monad' transformer stack you can use:\n--\n-- @\n-- 'views' :: 'MonadReader' s m             => 'Getter' s a     -> (a -> r) -> m r\n-- 'views' :: ('MonadReader' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Fold.Fold' s a       -> (a -> r) -> m r\n-- 'views' :: 'MonadReader' s m             => 'Control.Lens.Iso.Iso'' s a       -> (a -> r) -> m r\n-- 'views' :: 'MonadReader' s m             => 'Lens'' s a      -> (a -> r) -> m r\n-- 'views' :: ('MonadReader' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> r) -> m r\n-- @\n--\n-- @\n-- 'views' :: 'MonadReader' s m => 'Getting' r s a -> (a -> r) -> m r\n-- @\nviews :: MonadReader s m => LensLike' (Const r) s a -> (a -> r) -> m r\nviews l f = Reader.asks (coerce l f)\n{-# INLINE views #-}\n\n-- | View the value pointed to by a 'Getter' or 'Lens' or the\n-- result of folding over all the results of a 'Control.Lens.Fold.Fold' or\n-- 'Control.Lens.Traversal.Traversal' that points at a monoidal values.\n--\n-- This is the same operation as 'view' with the arguments flipped.\n--\n-- The fixity and semantics are such that subsequent field accesses can be\n-- performed with ('Prelude..').\n--\n-- >>> (a,b)^._2\n-- b\n--\n-- >>> (\"hello\",\"world\")^._2\n-- \"world\"\n--\n-- >>> import Data.Complex\n-- >>> ((0, 1 :+ 2), 3)^._1._2.to magnitude\n-- 2.23606797749979\n--\n-- @\n-- ('^.') ::             s -> 'Getter' s a     -> a\n-- ('^.') :: 'Data.Monoid.Monoid' m => s -> 'Control.Lens.Fold.Fold' s m       -> m\n-- ('^.') ::             s -> 'Control.Lens.Iso.Iso'' s a       -> a\n-- ('^.') ::             s -> 'Lens'' s a      -> a\n-- ('^.') :: 'Data.Monoid.Monoid' m => s -> 'Control.Lens.Traversal.Traversal'' s m -> m\n-- @\n(^.) :: s -> Getting a s a -> a\ns ^. l = getConst (l Const s)\n{-# INLINE (^.) #-}\n\n-------------------------------------------------------------------------------\n-- MonadState\n-------------------------------------------------------------------------------\n\n-- | Use the target of a 'Lens', 'Control.Lens.Iso.Iso', or\n-- 'Getter' in the current state, or use a summary of a\n-- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that points\n-- to a monoidal value.\n--\n-- >>> evalState (use _1) (a,b)\n-- a\n--\n-- >>> evalState (use _1) (\"hello\",\"world\")\n-- \"hello\"\n--\n-- @\n-- 'use' :: 'MonadState' s m             => 'Getter' s a     -> m a\n-- 'use' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Fold.Fold' s r       -> m r\n-- 'use' :: 'MonadState' s m             => 'Control.Lens.Iso.Iso'' s a       -> m a\n-- 'use' :: 'MonadState' s m             => 'Lens'' s a      -> m a\n-- 'use' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Traversal.Traversal'' s r -> m r\n-- @\nuse :: MonadState s m => Getting a s a -> m a\nuse l = State.gets (view l)\n{-# INLINE use #-}\n\n-- | Use the target of a 'Lens', 'Control.Lens.Iso.Iso' or\n-- 'Getter' in the current state, or use a summary of a\n-- 'Control.Lens.Fold.Fold' or 'Control.Lens.Traversal.Traversal' that\n-- points to a monoidal value.\n--\n-- >>> evalState (uses _1 length) (\"hello\",\"world\")\n-- 5\n--\n-- @\n-- 'uses' :: 'MonadState' s m             => 'Getter' s a     -> (a -> r) -> m r\n-- 'uses' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Fold.Fold' s a       -> (a -> r) -> m r\n-- 'uses' :: 'MonadState' s m             => 'Lens'' s a      -> (a -> r) -> m r\n-- 'uses' :: 'MonadState' s m             => 'Control.Lens.Iso.Iso'' s a       -> (a -> r) -> m r\n-- 'uses' :: ('MonadState' s m, 'Data.Monoid.Monoid' r) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> r) -> m r\n-- @\n--\n-- @\n-- 'uses' :: 'MonadState' s m => 'Getting' r s t a b -> (a -> r) -> m r\n-- @\nuses :: MonadState s m => LensLike' (Const r) s a -> (a -> r) -> m r\nuses l f = State.gets (views l f)\n{-# INLINE uses #-}\n\n-- | This is a generalized form of 'listen' that only extracts the portion of\n-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'\n-- then a monoidal summary of the parts of the log that are visited will be\n-- returned.\n--\n-- @\n-- 'listening' :: 'MonadWriter' w m             => 'Getter' w u     -> m a -> m (a, u)\n-- 'listening' :: 'MonadWriter' w m             => 'Lens'' w u      -> m a -> m (a, u)\n-- 'listening' :: 'MonadWriter' w m             => 'Iso'' w u       -> m a -> m (a, u)\n-- 'listening' :: ('MonadWriter' w m, 'Monoid' u) => 'Fold' w u       -> m a -> m (a, u)\n-- 'listening' :: ('MonadWriter' w m, 'Monoid' u) => 'Traversal'' w u -> m a -> m (a, u)\n-- 'listening' :: ('MonadWriter' w m, 'Monoid' u) => 'Prism'' w u     -> m a -> m (a, u)\n-- @\nlistening :: MonadWriter w m => Getting u w u -> m a -> m (a, u)\nlistening l m = do\n  (a, w) <- listen m\n  return (a, view l w)\n{-# INLINE listening #-}\n\n-- | This is a generalized form of 'listen' that only extracts the portion of\n-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'\n-- then a monoidal summary of the parts of the log that are visited will be\n-- returned.\n--\n-- @\n-- 'ilistening' :: 'MonadWriter' w m             => 'IndexedGetter' i w u     -> m a -> m (a, (i, u))\n-- 'ilistening' :: 'MonadWriter' w m             => 'IndexedLens'' i w u      -> m a -> m (a, (i, u))\n-- 'ilistening' :: ('MonadWriter' w m, 'Monoid' u) => 'IndexedFold' i w u       -> m a -> m (a, (i, u))\n-- 'ilistening' :: ('MonadWriter' w m, 'Monoid' u) => 'IndexedTraversal'' i w u -> m a -> m (a, (i, u))\n-- @\nilistening :: MonadWriter w m => IndexedGetting i (i, u) w u -> m a -> m (a, (i, u))\nilistening l m = do\n  (a, w) <- listen m\n  return (a, iview l w)\n{-# INLINE ilistening #-}\n\n-- | This is a generalized form of 'listen' that only extracts the portion of\n-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'\n-- then a monoidal summary of the parts of the log that are visited will be\n-- returned.\n--\n-- @\n-- 'listenings' :: 'MonadWriter' w m             => 'Getter' w u     -> (u -> v) -> m a -> m (a, v)\n-- 'listenings' :: 'MonadWriter' w m             => 'Lens'' w u      -> (u -> v) -> m a -> m (a, v)\n-- 'listenings' :: 'MonadWriter' w m             => 'Iso'' w u       -> (u -> v) -> m a -> m (a, v)\n-- 'listenings' :: ('MonadWriter' w m, 'Monoid' v) => 'Fold' w u       -> (u -> v) -> m a -> m (a, v)\n-- 'listenings' :: ('MonadWriter' w m, 'Monoid' v) => 'Traversal'' w u -> (u -> v) -> m a -> m (a, v)\n-- 'listenings' :: ('MonadWriter' w m, 'Monoid' v) => 'Prism'' w u     -> (u -> v) -> m a -> m (a, v)\n-- @\nlistenings :: MonadWriter w m => Getting v w u -> (u -> v) -> m a -> m (a, v)\nlistenings l uv m = do\n  (a, w) <- listen m\n  return (a, views l uv w)\n{-# INLINE listenings #-}\n\n-- | This is a generalized form of 'listen' that only extracts the portion of\n-- the log that is focused on by a 'Getter'. If given a 'Fold' or a 'Traversal'\n-- then a monoidal summary of the parts of the log that are visited will be\n-- returned.\n--\n-- @\n-- 'ilistenings' :: 'MonadWriter' w m             => 'IndexedGetter' w u     -> (i -> u -> v) -> m a -> m (a, v)\n-- 'ilistenings' :: 'MonadWriter' w m             => 'IndexedLens'' w u      -> (i -> u -> v) -> m a -> m (a, v)\n-- 'ilistenings' :: ('MonadWriter' w m, 'Monoid' v) => 'IndexedFold' w u       -> (i -> u -> v) -> m a -> m (a, v)\n-- 'ilistenings' :: ('MonadWriter' w m, 'Monoid' v) => 'IndexedTraversal'' w u -> (i -> u -> v) -> m a -> m (a, v)\n-- @\nilistenings :: MonadWriter w m => IndexedGetting i v w u -> (i -> u -> v) -> m a -> m (a, v)\nilistenings l iuv m = do\n  (a, w) <- listen m\n  return (a, iviews l iuv w)\n{-# INLINE ilistenings #-}\n\n------------------------------------------------------------------------------\n-- Indexed Getters\n------------------------------------------------------------------------------\n\n-- | View the index and value of an 'IndexedGetter' into the current environment as a pair.\n--\n-- When applied to an 'IndexedFold' the result will most likely be a nonsensical monoidal summary of\n-- the indices tupled with a monoidal summary of the values and probably not whatever it is you wanted.\niview :: MonadReader s m => IndexedGetting i (i,a) s a -> m (i,a)\niview l = asks (getConst #. l (Indexed $ \\i -> Const #. (,) i))\n{-# INLINE iview #-}\n\n-- | View a function of the index and value of an 'IndexedGetter' into the current environment.\n--\n-- When applied to an 'IndexedFold' the result will be a monoidal summary instead of a single answer.\n--\n-- @\n-- 'iviews' \u2261 'Control.Lens.Fold.ifoldMapOf'\n-- @\niviews :: MonadReader s m => IndexedGetting i r s a -> (i -> a -> r) -> m r\niviews l f = asks (coerce l f)\n{-# INLINE iviews #-}\n\n-- | Use the index and value of an 'IndexedGetter' into the current state as a pair.\n--\n-- When applied to an 'IndexedFold' the result will most likely be a nonsensical monoidal summary of\n-- the indices tupled with a monoidal summary of the values and probably not whatever it is you wanted.\niuse :: MonadState s m => IndexedGetting i (i,a) s a -> m (i,a)\niuse l = gets (getConst #. l (Indexed $ \\i -> Const #. (,) i))\n{-# INLINE iuse #-}\n\n-- | Use a function of the index and value of an 'IndexedGetter' into the current state.\n--\n-- When applied to an 'IndexedFold' the result will be a monoidal summary instead of a single answer.\niuses :: MonadState s m => IndexedGetting i r s a -> (i -> a -> r) -> m r\niuses l f = gets (coerce l f)\n{-# INLINE iuses #-}\n\n-- | View the index and value of an 'IndexedGetter' or 'IndexedLens'.\n--\n-- This is the same operation as 'iview' with the arguments flipped.\n--\n-- The fixity and semantics are such that subsequent field accesses can be\n-- performed with ('Prelude..').\n--\n-- @\n-- ('^@.') :: s -> 'IndexedGetter' i s a -> (i, a)\n-- ('^@.') :: s -> 'IndexedLens'' i s a  -> (i, a)\n-- @\n--\n-- The result probably doesn't have much meaning when applied to an 'IndexedFold'.\n(^@.) :: s -> IndexedGetting i (i, a) s a -> (i, a)\ns ^@. l = getConst $ l (Indexed $ \\i -> Const #. (,) i) s\n{-# INLINE (^@.) #-}\n\n-- | Coerce a 'Getter'-compatible 'Optical' to an 'Optical''. This\n-- is useful when using a 'Traversal' that is not simple as a 'Getter' or a\n-- 'Fold'.\n--\n-- @\n-- 'getting' :: 'Traversal' s t a b          -> 'Fold' s a\n-- 'getting' :: 'Lens' s t a b               -> 'Getter' s a\n-- 'getting' :: 'IndexedTraversal' i s t a b -> 'IndexedFold' i s a\n-- 'getting' :: 'IndexedLens' i s t a b      -> 'IndexedGetter' i s a\n-- @\ngetting :: (Profunctor p, Profunctor q, Functor f, Contravariant f)\n        => Optical p q f s t a b -> Optical' p q f s a\ngetting l f = rmap phantom . l $ rmap phantom f\n\n----------------------------------------------------------------------------\n-- Profunctors\n----------------------------------------------------------------------------\n\n-- | Formally, the class 'Profunctor' represents a profunctor\n-- from @Hask@ -> @Hask@.\n--\n-- Intuitively it is a bifunctor where the first argument is contravariant\n-- and the second argument is covariant.\n--\n-- You can define a 'Profunctor' by either defining 'dimap' or by defining both\n-- 'lmap' and 'rmap'.\n--\n-- If you supply 'dimap', you should ensure that:\n--\n-- @'dimap' 'id' 'id' \u2261 'id'@\n--\n-- If you supply 'lmap' and 'rmap', ensure:\n--\n-- @\n-- 'lmap' 'id' \u2261 'id'\n-- 'rmap' 'id' \u2261 'id'\n-- @\n--\n-- If you supply both, you should also ensure:\n--\n-- @'dimap' f g \u2261 'lmap' f '.' 'rmap' g@\n--\n-- These ensure by parametricity:\n--\n-- @\n-- 'dimap' (f '.' g) (h '.' i) \u2261 'dimap' g h '.' 'dimap' f i\n-- 'lmap' (f '.' g) \u2261 'lmap' g '.' 'lmap' f\n-- 'rmap' (f '.' g) \u2261 'rmap' f '.' 'rmap' g\n-- @\nclass Profunctor p where\n  -- | Map over both arguments at the same time.\n  --\n  -- @'dimap' f g \u2261 'lmap' f '.' 'rmap' g@\n  dimap :: (a -> b) -> (c -> d) -> p b c -> p a d\n  dimap f g = lmap f . rmap g\n  {-# INLINE dimap #-}\n\n  -- | Map the first argument contravariantly.\n  --\n  -- @'lmap' f \u2261 'dimap' f 'id'@\n  lmap :: (a -> b) -> p b c -> p a c\n  lmap f = dimap f id\n  {-# INLINE lmap #-}\n\n  -- | Map the second argument covariantly.\n  --\n  -- @'rmap' \u2261 'dimap' 'id'@\n  rmap :: (b -> c) -> p a b -> p a c\n  rmap = dimap id\n  {-# INLINE rmap #-}\n\n  -- | Strictly map the second argument argument\n  -- covariantly with a function that is assumed\n  -- operationally to be a cast, such as a newtype\n  -- constructor.\n  --\n  -- /Note:/ This operation is explicitly /unsafe/\n  -- since an implementation may choose to use\n  -- 'unsafeCoerce' to implement this combinator\n  -- and it has no way to validate that your function\n  -- meets the requirements.\n  --\n  -- If you implement this combinator with\n  -- 'unsafeCoerce', then you are taking upon yourself\n  -- the obligation that you don't use GADT-like\n  -- tricks to distinguish values.\n  --\n  -- If you import \"Data.Profunctor.Unsafe\" you are\n  -- taking upon yourself the obligation that you\n  -- will only call this with a first argument that is\n  -- operationally identity.\n  --\n  -- The semantics of this function with respect to bottoms\n  -- should match the default definition:\n  --\n  -- @('Profuctor.Unsafe.#.') \u2261 \\\\_ -> \\\\p -> p \\`seq\\` 'rmap' 'coerce' p@\n  (#.) :: forall a b c q. Coercible c b => q b c -> p a b -> p a c\n  (#.) = \\_ -> \\p -> p `seq` rmap (coerce (id :: c -> c) :: b -> c) p\n  {-# INLINE (#.) #-}\n\n  -- | Strictly map the first argument argument\n  -- contravariantly with a function that is assumed\n  -- operationally to be a cast, such as a newtype\n  -- constructor.\n  --\n  -- /Note:/ This operation is explicitly /unsafe/\n  -- since an implementation may choose to use\n  -- 'unsafeCoerce' to implement this combinator\n  -- and it has no way to validate that your function\n  -- meets the requirements.\n  --\n  -- If you implement this combinator with\n  -- 'unsafeCoerce', then you are taking upon yourself\n  -- the obligation that you don't use GADT-like\n  -- tricks to distinguish values.\n  --\n  -- If you import \"Data.Profunctor.Unsafe\" you are\n  -- taking upon yourself the obligation that you\n  -- will only call this with a second argument that is\n  -- operationally identity.\n  --\n  -- @('.#') \u2261 \\\\p -> p \\`seq\\` \\\\f -> 'lmap' 'coerce' p@\n  (.#) :: forall a b c q. Coercible b a => p b c -> q a b -> p a c\n  (.#) = \\p -> p `seq` \\_ -> lmap (coerce (id :: b -> b) :: a -> b) p\n  {-# INLINE (.#) #-}\n\n  {-# MINIMAL dimap | (lmap, rmap) #-}\n\n------------------------------------------------------------------------------\n-- Conjoined\n------------------------------------------------------------------------------\n\n-- | This is a 'Profunctor' that is both 'Corepresentable' by @f@ and 'Representable' by @g@ such\n-- that @f@ is left adjoint to @g@. From this you can derive a lot of structure due\n-- to the preservation of limits and colimits.\nclass\n  ( Choice p, Corepresentable p, Comonad (Corep p), Traversable (Corep p)\n  , Strong p, Representable p, Monad (Rep p), MonadFix (Rep p), Costrong p, ArrowLoop p, ArrowApply p, ArrowChoice p\n  ) => Conjoined p where\n\n  -- | 'Conjoined' is strong enough to let us distribute every 'Conjoined'\n  -- 'Profunctor' over every Haskell 'Functor'. This is effectively a\n  -- generalization of 'fmap'.\n  distrib :: Functor f => p a b -> p (f a) (f b)\n  distrib = tabulate . collect . sieve\n  {-# INLINE distrib #-}\n\n  -- | This permits us to make a decision at an outermost point about whether or not we use an index.\n  --\n  -- Ideally any use of this function should be done in such a way so that you compute the same answer,\n  -- but this cannot be enforced at the type level.\n  conjoined :: ((p ~ (->)) => q (a -> b) r) -> q (p a b) r -> q (p a b) r\n  conjoined _ r = r\n  {-# INLINE conjoined #-}\n\ninstance Conjoined (->) where\n  distrib = fmap\n  {-# INLINE distrib #-}\n  conjoined l _ = l\n  {-# INLINE conjoined #-}\n\n----------------------------------------------------------------------------\n-- Indexable\n----------------------------------------------------------------------------\n\n-- | This class permits overloading of function application for things that\n-- also admit a notion of a key or index.\nclass Conjoined p => Indexable i p where\n  -- | Build a function from an 'indexed' function.\n  indexed :: p a b -> i -> a -> b\n\ninstance Indexable i (->) where\n  indexed = const\n  {-# INLINE indexed #-}\n\n-----------------------------------------------------------------------------\n-- Indexed Internals\n-----------------------------------------------------------------------------\n\n-- | A function with access to a index. This constructor may be useful when you need to store\n-- an 'Indexable' in a container to avoid @ImpredicativeTypes@.\n--\n-- @index :: Indexed i a b -> i -> a -> b@\nnewtype Indexed i a b = Indexed { runIndexed :: i -> a -> b }\n\ninstance Functor (Indexed i a) where\n  fmap g (Indexed f) = Indexed $ \\i a -> g (f i a)\n  {-# INLINE fmap #-}\n\ninstance Apply (Indexed i a) where\n  Indexed f <.> Indexed g = Indexed $ \\i a -> f i a (g i a)\n  {-# INLINE (<.>) #-}\n\ninstance Applicative (Indexed i a) where\n  pure b = Indexed $ \\_ _ -> b\n  {-# INLINE pure #-}\n  Indexed f <*> Indexed g = Indexed $ \\i a -> f i a (g i a)\n  {-# INLINE (<*>) #-}\n\ninstance Monad (Indexed i a) where\n  return = pure\n  {-# INLINE return #-}\n  Indexed f >>= k = Indexed $ \\i a -> runIndexed (k (f i a)) i a\n  {-# INLINE (>>=) #-}\n\ninstance MonadFix (Indexed i a) where\n  mfix f = Indexed $ \\ i a -> let o = runIndexed (f o) i a in o\n  {-# INLINE mfix #-}\n\ninstance Profunctor (Indexed i) where\n  dimap ab cd ibc = Indexed $ \\i -> cd . runIndexed ibc i . ab\n  {-# INLINE dimap #-}\n  lmap ab ibc = Indexed $ \\i -> runIndexed ibc i . ab\n  {-# INLINE lmap #-}\n  rmap bc iab = Indexed $ \\i -> bc . runIndexed iab i\n  {-# INLINE rmap #-}\n  (.#) ibc _ = coerce ibc\n  {-# INLINE (.#) #-}\n  (#.) _ = coerce\n  {-# INLINE (#.) #-}\n\ninstance Costrong (Indexed i) where\n  unfirst (Indexed iadbd) = Indexed $ \\i a -> let\n      (b, d) = iadbd i (a, d)\n    in b\n\ninstance Sieve (Indexed i) ((->) i) where\n  sieve = flip . runIndexed\n  {-# INLINE sieve #-}\n\ninstance Representable (Indexed i) where\n  type Rep (Indexed i) = (->) i\n  tabulate = Indexed . flip\n  {-# INLINE tabulate #-}\n\ninstance Cosieve (Indexed i) ((,) i) where\n  cosieve = uncurry . runIndexed\n  {-# INLINE cosieve #-}\n\ninstance Corepresentable (Indexed i) where\n  type Corep (Indexed i) = (,) i\n  cotabulate = Indexed . curry\n  {-# INLINE cotabulate #-}\n\ninstance Choice (Indexed i) where\n  right' = right\n  {-# INLINE right' #-}\n\ninstance Strong (Indexed i) where\n  second' = Arrow.second\n  {-# INLINE second' #-}\n\ninstance C.Category (Indexed i) where\n  id = Indexed (const id)\n  {-# INLINE id #-}\n  Indexed f . Indexed g = Indexed $ \\i -> f i . g i\n  {-# INLINE (.) #-}\n\ninstance Arrow (Indexed i) where\n  arr f = Indexed (\\_ -> f)\n  {-# INLINE arr #-}\n  first f = Indexed (Arrow.first . runIndexed f)\n  {-# INLINE first #-}\n  second f = Indexed (Arrow.second . runIndexed f)\n  {-# INLINE second #-}\n  Indexed f *** Indexed g = Indexed $ \\i -> f i *** g i\n  {-# INLINE (***) #-}\n  Indexed f &&& Indexed g = Indexed $ \\i -> f i &&& g i\n  {-# INLINE (&&&) #-}\n\ninstance ArrowChoice (Indexed i) where\n  left f = Indexed (left . runIndexed f)\n  {-# INLINE left #-}\n  right f = Indexed (right . runIndexed f)\n  {-# INLINE right #-}\n  Indexed f +++ Indexed g = Indexed $ \\i -> f i +++ g i\n  {-# INLINE (+++)  #-}\n  Indexed f ||| Indexed g = Indexed $ \\i -> f i ||| g i\n  {-# INLINE (|||) #-}\n\ninstance ArrowApply (Indexed i) where\n  app = Indexed $ \\ i (f, b) -> runIndexed f i b\n  {-# INLINE app #-}\n\ninstance ArrowLoop (Indexed i) where\n  loop (Indexed f) = Indexed $ \\i b -> let (c,d) = f i (b, d) in c\n  {-# INLINE loop #-}\n\ninstance Conjoined (Indexed i) where\n  distrib (Indexed iab) = Indexed $ \\i fa -> iab i <$> fa\n  {-# INLINE distrib #-}\n\ninstance i ~ j => Indexable i (Indexed j) where\n  indexed = runIndexed\n  {-# INLINE indexed #-}\n\n------------------------------------------------------------------------------\n-- Indexing\n------------------------------------------------------------------------------\n\n-- | 'Applicative' composition of @'Control.Monad.Trans.State.Lazy.State' 'Int'@ with a 'Functor', used\n-- by 'Control.Lens.Indexed.indexed'.\nnewtype Indexing f a = Indexing { runIndexing :: Int -> (Int, f a) }\n\ninstance Functor f => Functor (Indexing f) where\n  fmap f (Indexing m) = Indexing $ \\i -> case m i of\n    (j, x) -> (j, fmap f x)\n  {-# INLINE fmap #-}\n\ninstance Apply f => Apply (Indexing f) where\n  Indexing mf <.> Indexing ma = Indexing $ \\i -> case mf i of\n    (j, ff) -> case ma j of\n       ~(k, fa) -> (k, ff <.> fa)\n  {-# INLINE (<.>) #-}\n\ninstance Applicative f => Applicative (Indexing f) where\n  pure x = Indexing $ \\i -> (i, pure x)\n  {-# INLINE pure #-}\n  Indexing mf <*> Indexing ma = Indexing $ \\i -> case mf i of\n    (j, ff) -> case ma j of\n       ~(k, fa) -> (k, ff <*> fa)\n  {-# INLINE (<*>) #-}\n\ninstance Contravariant f => Contravariant (Indexing f) where\n  contramap f (Indexing m) = Indexing $ \\i -> case m i of\n    (j, ff) -> (j, contramap f ff)\n  {-# INLINE contramap #-}\n\ninstance Semigroup (f a) => Semigroup (Indexing f a) where\n    Indexing mx <> Indexing my = Indexing $ \\i -> case mx i of\n      (j, x) -> case my j of\n         ~(k, y) -> (k, x <> y)\n    {-# INLINE (<>) #-}\n\n-- |\n--\n-- >>> \"cat\" ^@.. (folded <> folded)\n-- [(0,'c'),(1,'a'),(2,'t'),(0,'c'),(1,'a'),(2,'t')]\n--\n-- >>> \"cat\" ^@.. indexing (folded <> folded)\n-- [(0,'c'),(1,'a'),(2,'t'),(3,'c'),(4,'a'),(5,'t')]\ninstance Monoid (f a) => Monoid (Indexing f a) where\n    mempty = Indexing $ \\i -> (i, mempty)\n    {-# INLINE mempty #-}\n\n-- | Transform a 'Control.Lens.Traversal.Traversal' into an 'Control.Lens.Traversal.IndexedTraversal' or\n-- a 'Control.Lens.Fold.Fold' into an 'Control.Lens.Fold.IndexedFold', etc.\n--\n-- @\n-- 'indexing' :: 'Control.Lens.Type.Traversal' s t a b -> 'Control.Lens.Type.IndexedTraversal' 'Int' s t a b\n-- 'indexing' :: 'Control.Lens.Type.Prism' s t a b     -> 'Control.Lens.Type.IndexedTraversal' 'Int' s t a b\n-- 'indexing' :: 'Control.Lens.Type.Lens' s t a b      -> 'Control.Lens.Type.IndexedLens' 'Int'  s t a b\n-- 'indexing' :: 'Control.Lens.Type.Iso' s t a b       -> 'Control.Lens.Type.IndexedLens' 'Int' s t a b\n-- 'indexing' :: 'Control.Lens.Type.Fold' s a          -> 'Control.Lens.Type.IndexedFold' 'Int' s a\n-- 'indexing' :: 'Control.Lens.Type.Getter' s a        -> 'Control.Lens.Type.IndexedGetter' 'Int' s a\n-- @\n--\n-- @'indexing' :: 'Indexable' 'Int' p => 'Control.Lens.Type.LensLike' ('Indexing' f) s t a b -> 'Control.Lens.Type.Over' p f s t a b@\nindexing :: Indexable Int p => ((a -> Indexing f b) -> s -> Indexing f t) -> p a (f b) -> s -> f t\nindexing l iafb s = snd $ runIndexing (l (\\a -> Indexing (\\i -> i `seq` (i + 1, indexed iafb i a))) s) 0\n{-# INLINE indexing #-}\n\n------------------------------------------------------------------------------\n-- Indexing64\n------------------------------------------------------------------------------\n\n-- | 'Applicative' composition of @'Control.Monad.Trans.State.Lazy.State' 'Int64'@ with a 'Functor', used\n-- by 'Control.Lens.Indexed.indexed64'.\nnewtype Indexing64 f a = Indexing64 { runIndexing64 :: Int64 -> (Int64, f a) }\n\ninstance Functor f => Functor (Indexing64 f) where\n  fmap f (Indexing64 m) = Indexing64 $ \\i -> case m i of\n    (j, x) -> (j, fmap f x)\n  {-# INLINE fmap #-}\n\ninstance Apply f => Apply (Indexing64 f) where\n  Indexing64 mf <.> Indexing64 ma = Indexing64 $ \\i -> case mf i of\n    (j, ff) -> case ma j of\n       ~(k, fa) -> (k, ff <.> fa)\n  {-# INLINE (<.>) #-}\n\ninstance Applicative f => Applicative (Indexing64 f) where\n  pure x = Indexing64 $ \\i -> (i, pure x)\n  {-# INLINE pure #-}\n  Indexing64 mf <*> Indexing64 ma = Indexing64 $ \\i -> case mf i of\n    (j, ff) -> case ma j of\n       ~(k, fa) -> (k, ff <*> fa)\n  {-# INLINE (<*>) #-}\n\ninstance Contravariant f => Contravariant (Indexing64 f) where\n  contramap f (Indexing64 m) = Indexing64 $ \\i -> case m i of\n    (j, ff) -> (j, contramap f ff)\n  {-# INLINE contramap #-}\n\n-- | Transform a 'Control.Lens.Traversal.Traversal' into an 'Control.Lens.Traversal.IndexedTraversal' or\n-- a 'Control.Lens.Fold.Fold' into an 'Control.Lens.Fold.IndexedFold', etc.\n--\n-- This combinator is like 'indexing' except that it handles large traversals and folds gracefully.\n--\n-- @\n-- 'indexing64' :: 'Control.Lens.Type.Traversal' s t a b -> 'Control.Lens.Type.IndexedTraversal' 'Int64' s t a b\n-- 'indexing64' :: 'Control.Lens.Type.Prism' s t a b     -> 'Control.Lens.Type.IndexedTraversal' 'Int64' s t a b\n-- 'indexing64' :: 'Control.Lens.Type.Lens' s t a b      -> 'Control.Lens.Type.IndexedLens' 'Int64' s t a b\n-- 'indexing64' :: 'Control.Lens.Type.Iso' s t a b       -> 'Control.Lens.Type.IndexedLens' 'Int64' s t a b\n-- 'indexing64' :: 'Control.Lens.Type.Fold' s a          -> 'Control.Lens.Type.IndexedFold' 'Int64' s a\n-- 'indexing64' :: 'Control.Lens.Type.Getter' s a        -> 'Control.Lens.Type.IndexedGetter' 'Int64' s a\n-- @\n--\n-- @'indexing64' :: 'Indexable' 'Int64' p => 'Control.Lens.Type.LensLike' ('Indexing64' f) s t a b -> 'Control.Lens.Type.Over' p f s t a b@\nindexing64 :: Indexable Int64 p => ((a -> Indexing64 f b) -> s -> Indexing64 f t) -> p a (f b) -> s -> f t\nindexing64 l iafb s = snd $ runIndexing64 (l (\\a -> Indexing64 (\\i -> i `seq` (i + 1, indexed iafb i a))) s) 0\n{-# INLINE indexing64 #-}\n\n-------------------------------------------------------------------------------\n-- Converting to Folds\n-------------------------------------------------------------------------------\n\n-- | Fold a container with indices returning both the indices and the values.\n--\n-- The result is only valid to compose in a 'Traversal', if you don't edit the\n-- index as edits to the index have no effect.\n--\n-- >>> [10, 20, 30] ^.. ifolded . withIndex\n-- [(0,10),(1,20),(2,30)]\n--\n-- >>> [10, 20, 30] ^.. ifolded . withIndex . alongside negated (re _Show)\n-- [(0,\"10\"),(-1,\"20\"),(-2,\"30\")]\n--\nwithIndex :: (Indexable i p, Functor f) => p (i, s) (f (j, t)) -> Indexed i s (f t)\nwithIndex f = Indexed $ \\i a -> snd <$> indexed f i (i, a)\n{-# INLINE withIndex #-}\n\n-- | When composed with an 'IndexedFold' or 'IndexedTraversal' this yields an\n-- ('Indexed') 'Fold' of the indices.\nasIndex :: (Indexable i p, Contravariant f, Functor f) => p i (f i) -> Indexed i s (f s)\nasIndex f = Indexed $ \\i _ -> phantom (indexed f i i)\n{-# INLINE asIndex #-}\n\n-- | A 'Lens' is actually a lens family as described in\n-- <http://comonad.com/reader/2012/mirrored-lenses/>.\n--\n-- With great power comes great responsibility and a 'Lens' is subject to the\n-- three common sense 'Lens' laws:\n--\n-- 1) You get back what you put in:\n--\n-- @\n-- 'Control.Lens.Getter.view' l ('Control.Lens.Setter.set' l v s)  \u2261 v\n-- @\n--\n-- 2) Putting back what you got doesn't change anything:\n--\n-- @\n-- 'Control.Lens.Setter.set' l ('Control.Lens.Getter.view' l s) s  \u2261 s\n-- @\n--\n-- 3) Setting twice is the same as setting once:\n--\n-- @\n-- 'Control.Lens.Setter.set' l v' ('Control.Lens.Setter.set' l v s) \u2261 'Control.Lens.Setter.set' l v' s\n-- @\n--\n-- These laws are strong enough that the 4 type parameters of a 'Lens' cannot\n-- vary fully independently. For more on how they interact, read the \\\"Why is\n-- it a Lens Family?\\\" section of\n-- <http://comonad.com/reader/2012/mirrored-lenses/>.\n--\n-- There are some emergent properties of these laws:\n--\n-- 1) @'Control.Lens.Setter.set' l s@ must be injective for every @s@ This is a consequence of law #1\n--\n-- 2) @'Control.Lens.Setter.set' l@ must be surjective, because of law #2, which indicates that it is possible to obtain any 'v' from some 's' such that @'Control.Lens.Setter.set' s v = s@\n--\n-- 3) Given just the first two laws you can prove a weaker form of law #3 where the values @v@ that you are setting match:\n--\n-- @\n-- 'Control.Lens.Setter.set' l v ('Control.Lens.Setter.set' l v s) \u2261 'Control.Lens.Setter.set' l v s\n-- @\n--\n-- Every 'Lens' can be used directly as a 'Control.Lens.Setter.Setter' or 'Traversal'.\n--\n-- You can also use a 'Lens' for 'Control.Lens.Getter.Getting' as if it were a\n-- 'Fold' or 'Getter'.\n--\n-- Since every 'Lens' is a valid 'Traversal', the\n-- 'Traversal' laws are required of any 'Lens' you create:\n--\n-- @\n-- l 'pure' \u2261 'pure'\n-- 'fmap' (l f) '.' l g \u2261 'Data.Functor.Compose.getCompose' '.' l ('Data.Functor.Compose.Compose' '.' 'fmap' f '.' g)\n-- @\n--\n-- @\n-- type 'Lens' s t a b = forall f. 'Functor' f => 'LensLike' f s t a b\n-- @\ntype Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t\n\n-- | @\n-- type 'Lens'' = 'Simple' 'Lens'\n-- @\ntype Lens' s a = Lens s s a a\n\n-- | Every 'IndexedLens' is a valid 'Lens' and a valid 'Control.Lens.Traversal.IndexedTraversal'.\ntype IndexedLens i s t a b = forall f p. (Indexable i p, Functor f) => p a (f b) -> s -> f t\n\n-- | @\n-- type 'IndexedLens'' i = 'Simple' ('IndexedLens' i)\n-- @\ntype IndexedLens' i s a = IndexedLens i s s a a\n\n-- | An 'IndexPreservingLens' leaves any index it is composed with alone.\ntype IndexPreservingLens s t a b = forall p f. (Conjoined p, Functor f) => p a (f b) -> p s (f t)\n\n-- | @\n-- type 'IndexPreservingLens'' = 'Simple' 'IndexPreservingLens'\n-- @\ntype IndexPreservingLens' s a = IndexPreservingLens s s a a\n\n------------------------------------------------------------------------------\n-- Traversals\n------------------------------------------------------------------------------\n\n-- | A 'Traversal' can be used directly as a 'Control.Lens.Setter.Setter' or a 'Fold' (but not as a 'Lens') and provides\n-- the ability to both read and update multiple fields, subject to some relatively weak 'Traversal' laws.\n--\n-- These have also been known as multilenses, but they have the signature and spirit of\n--\n-- @\n-- 'Data.Traversable.traverse' :: 'Data.Traversable.Traversable' f => 'Traversal' (f a) (f b) a b\n-- @\n--\n-- and the more evocative name suggests their application.\n--\n-- Most of the time the 'Traversal' you will want to use is just 'Data.Traversable.traverse', but you can also pass any\n-- 'Lens' or 'Iso' as a 'Traversal', and composition of a 'Traversal' (or 'Lens' or 'Iso') with a 'Traversal' (or 'Lens' or 'Iso')\n-- using ('.') forms a valid 'Traversal'.\n--\n-- The laws for a 'Traversal' @t@ follow from the laws for 'Data.Traversable.Traversable' as stated in \\\"The Essence of the Iterator Pattern\\\".\n--\n-- @\n-- t 'pure' \u2261 'pure'\n-- 'fmap' (t f) '.' t g \u2261 'Data.Functor.Compose.getCompose' '.' t ('Data.Functor.Compose.Compose' '.' 'fmap' f '.' g)\n-- @\n--\n-- One consequence of this requirement is that a 'Traversal' needs to leave the same number of elements as a\n-- candidate for subsequent 'Traversal' that it started with. Another testament to the strength of these laws\n-- is that the caveat expressed in section 5.5 of the \\\"Essence of the Iterator Pattern\\\" about exotic\n-- 'Data.Traversable.Traversable' instances that 'Data.Traversable.traverse' the same entry multiple times was actually already ruled out by the\n-- second law in that same paper!\ntype Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t\n\n-- | @\n-- type 'Traversal'' = 'Simple' 'Traversal'\n-- @\ntype Traversal' s a = Traversal s s a a\n\n-- | A 'Traversal' which targets at least one element.\n--\n-- Note that since 'Apply' is not a superclass of 'Applicative', a 'Traversal1'\n-- cannot always be used in place of a 'Traversal'. In such circumstances\n-- 'Control.Lens.Traversal.cloneTraversal' will convert a 'Traversal1' into a 'Traversal'.\ntype Traversal1 s t a b = forall f. Apply f => (a -> f b) -> s -> f t\ntype Traversal1' s a = Traversal1 s s a a\n\n-- | Every 'IndexedTraversal' is a valid 'Control.Lens.Traversal.Traversal' or\n-- 'Control.Lens.Fold.IndexedFold'.\n--\n-- The 'Indexed' constraint is used to allow an 'IndexedTraversal' to be used\n-- directly as a 'Control.Lens.Traversal.Traversal'.\n--\n-- The 'Control.Lens.Traversal.Traversal' laws are still required to hold.\n--\n-- In addition, the index @i@ should satisfy the requirement that it stays\n-- unchanged even when modifying the value @a@, otherwise traversals like\n-- 'indices' break the 'Traversal' laws.\ntype IndexedTraversal i s t a b = forall p f. (Indexable i p, Applicative f) => p a (f b) -> s -> f t\n\n-- | @\n-- type 'IndexedTraversal'' i = 'Simple' ('IndexedTraversal' i)\n-- @\ntype IndexedTraversal' i s a = IndexedTraversal i s s a a\n\ntype IndexedTraversal1 i s t a b = forall p f. (Indexable i p, Apply f) => p a (f b) -> s -> f t\ntype IndexedTraversal1' i s a = IndexedTraversal1 i s s a a\n\n-- | An 'IndexPreservingLens' leaves any index it is composed with alone.\ntype IndexPreservingTraversal s t a b = forall p f. (Conjoined p, Applicative f) => p a (f b) -> p s (f t)\n\n-- | @\n-- type 'IndexPreservingTraversal'' = 'Simple' 'IndexPreservingTraversal'\n-- @\ntype IndexPreservingTraversal' s a = IndexPreservingTraversal s s a a\n\ntype IndexPreservingTraversal1 s t a b = forall p f. (Conjoined p, Apply f) => p a (f b) -> p s (f t)\ntype IndexPreservingTraversal1' s a = IndexPreservingTraversal1 s s a a\n\n------------------------------------------------------------------------------\n-- Setters\n------------------------------------------------------------------------------\n\n-- | The only 'LensLike' law that can apply to a 'Setter' @l@ is that\n--\n-- @\n-- 'Control.Lens.Setter.set' l y ('Control.Lens.Setter.set' l x a) \u2261 'Control.Lens.Setter.set' l y a\n-- @\n--\n-- You can't 'Control.Lens.Getter.view' a 'Setter' in general, so the other two laws are irrelevant.\n--\n-- However, two 'Functor' laws apply to a 'Setter':\n--\n-- @\n-- 'Control.Lens.Setter.over' l 'id' \u2261 'id'\n-- 'Control.Lens.Setter.over' l f '.' 'Control.Lens.Setter.over' l g \u2261 'Control.Lens.Setter.over' l (f '.' g)\n-- @\n--\n-- These can be stated more directly:\n--\n-- @\n-- l 'pure' \u2261 'pure'\n-- l f '.' 'untainted' '.' l g \u2261 l (f '.' 'untainted' '.' g)\n-- @\n--\n-- You can compose a 'Setter' with a 'Lens' or a 'Traversal' using ('.') from the @Prelude@\n-- and the result is always only a 'Setter' and nothing more.\n--\n-- >>> over traverse f [a,b,c,d]\n-- [f a,f b,f c,f d]\n--\n-- >>> over _1 f (a,b)\n-- (f a,b)\n--\n-- >>> over (traverse._1) f [(a,b),(c,d)]\n-- [(f a,b),(f c,d)]\n--\n-- >>> over both f (a,b)\n-- (f a,f b)\n--\n-- >>> over (traverse.both) f [(a,b),(c,d)]\n-- [(f a,f b),(f c,f d)]\ntype Setter s t a b = forall f. Settable f => (a -> f b) -> s -> f t\n\n-- | A 'Setter'' is just a 'Setter' that doesn't change the types.\n--\n-- These are particularly common when talking about monomorphic containers. /e.g./\n--\n-- @\n-- 'sets' Data.Text.map :: 'Setter'' 'Data.Text.Internal.Text' 'Char'\n-- @\n--\n-- @\n-- type 'Setter'' = 'Simple' 'Setter'\n-- @\ntype Setter' s a = Setter s s a a\n\n-- | Every 'IndexedSetter' is a valid 'Setter'.\n--\n-- The 'Setter' laws are still required to hold.\ntype IndexedSetter i s t a b = forall f p.\n  (Indexable i p, Settable f) => p a (f b) -> s -> f t\n\n-- | @\n-- type 'IndexedSetter'' i = 'Simple' ('IndexedSetter' i)\n-- @\ntype IndexedSetter' i s a = IndexedSetter i s s a a\n\n-- | An 'IndexPreservingSetter' can be composed with a 'IndexedSetter', 'IndexedTraversal' or 'IndexedLens'\n-- and leaves the index intact, yielding an 'IndexedSetter'.\ntype IndexPreservingSetter s t a b = forall p f. (Conjoined p, Settable f) => p a (f b) -> p s (f t)\n\n-- | @\n-- type 'IndexedPreservingSetter'' i = 'Simple' 'IndexedPreservingSetter'\n-- @\ntype IndexPreservingSetter' s a = IndexPreservingSetter s s a a\n\n-----------------------------------------------------------------------------\n-- Isomorphisms\n-----------------------------------------------------------------------------\n\n-- | Isomorphism families can be composed with another 'Lens' using ('.') and 'id'.\n--\n-- Since every 'Iso' is both a valid 'Lens' and a valid 'Prism', the laws for those types\n-- imply the following laws for an 'Iso' 'f':\n--\n-- @\n-- f '.' 'Control.Lens.Iso.from' f \u2261 'id'\n-- 'Control.Lens.Iso.from' f '.' f \u2261 'id'\n-- @\n--\n-- Note: Composition with an 'Iso' is index- and measure- preserving.\ntype Iso s t a b = forall p f. (Profunctor p, Functor f) => p a (f b) -> p s (f t)\n\n-- | @\n-- type 'Iso'' = 'Control.Lens.Type.Simple' 'Iso'\n-- @\ntype Iso' s a = Iso s s a a\n\n------------------------------------------------------------------------------\n-- Review Internals\n------------------------------------------------------------------------------\n\n-- | This is a limited form of a 'Prism' that can only be used for 're' operations.\n--\n-- Like with a 'Getter', there are no laws to state for a 'Review'.\n--\n-- You can generate a 'Review' by using 'unto'. You can also use any 'Prism' or 'Iso'\n-- directly as a 'Review'.\ntype Review t b = forall p f. (Choice p, Bifunctor p, Settable f) => Optic' p f t b\n\n-- | If you see this in a signature for a function, the function is expecting a 'Review'\n-- (in practice, this usually means a 'Prism').\ntype AReview t b = Optic' Tagged Identity t b\n\n------------------------------------------------------------------------------\n-- Prism Internals\n------------------------------------------------------------------------------\n\n-- | A 'Prism' @l@ is a 'Traversal' that can also be turned\n-- around with 'Control.Lens.Review.re' to obtain a 'Getter' in the\n-- opposite direction.\n--\n-- There are three laws that a 'Prism' should satisfy:\n--\n-- First, if I 'Control.Lens.Review.re' or 'Control.Lens.Review.review' a value with a 'Prism' and then 'Control.Lens.Fold.preview' or use ('Control.Lens.Fold.^?'), I will get it back:\n--\n-- @\n-- 'Control.Lens.Fold.preview' l ('Control.Lens.Review.review' l b) \u2261 'Just' b\n-- @\n--\n-- Second, if you can extract a value @a@ using a 'Prism' @l@ from a value @s@, then the value @s@ is completely described by @l@ and @a@:\n--\n-- @\n-- 'Control.Lens.Fold.preview' l s \u2261 'Just' a \u27f9 'Control.Lens.Review.review' l a \u2261 s\n-- @\n--\n-- Third, if you get non-match @t@, you can convert it result back to @s@:\n--\n-- @\n-- 'Control.Lens.Combinators.matching' l s \u2261 'Left' t \u27f9 'Control.Lens.Combinators.matching' l t \u2261 'Left' s\n-- @\n--\n-- The first two laws imply that the 'Traversal' laws hold for every 'Prism' and that we 'Data.Traversable.traverse' at most 1 element:\n--\n-- @\n-- 'Control.Lens.Fold.lengthOf' l x '<=' 1\n-- @\n--\n-- It may help to think of this as an 'Iso' that can be partial in one direction.\n--\n-- Every 'Prism' is a valid 'Traversal'.\n--\n-- Every 'Iso' is a valid 'Prism'.\n--\n-- For example, you might have a @'Prism'' 'Integer' 'Numeric.Natural.Natural'@ allows you to always\n-- go from a 'Numeric.Natural.Natural' to an 'Integer', and provide you with tools to check if an 'Integer' is\n-- a 'Numeric.Natural.Natural' and/or to edit one if it is.\n--\n--\n-- @\n-- 'nat' :: 'Prism'' 'Integer' 'Numeric.Natural.Natural'\n-- 'nat' = 'Control.Lens.Prism.prism' 'toInteger' '$' \\\\ i ->\n--    if i '<' 0\n--    then 'Left' i\n--    else 'Right' ('fromInteger' i)\n-- @\n--\n-- Now we can ask if an 'Integer' is a 'Numeric.Natural.Natural'.\n--\n-- >>> 5^?nat\n-- Just 5\n--\n-- >>> (-5)^?nat\n-- Nothing\n--\n-- We can update the ones that are:\n--\n-- >>> (-3,4) & both.nat *~ 2\n-- (-3,8)\n--\n-- And we can then convert from a 'Numeric.Natural.Natural' to an 'Integer'.\n--\n-- >>> 5 ^. re nat -- :: Natural\n-- 5\n--\n-- Similarly we can use a 'Prism' to 'Data.Traversable.traverse' the 'Left' half of an 'Either':\n--\n-- >>> Left \"hello\" & _Left %~ length\n-- Left 5\n--\n-- or to construct an 'Either':\n--\n-- >>> 5^.re _Left\n-- Left 5\n--\n-- such that if you query it with the 'Prism', you will get your original input back.\n--\n-- >>> 5^.re _Left ^? _Left\n-- Just 5\n--\n-- Another interesting way to think of a 'Prism' is as the categorical dual of a 'Lens'\n-- -- a co-'Lens', so to speak. This is what permits the construction of 'Control.Lens.Prism.outside'.\n--\n-- Note: Composition with a 'Prism' is index-preserving.\ntype Prism s t a b = forall p f. (Choice p, Applicative f) => p a (f b) -> p s (f t)\n\n-- | A 'Simple' 'Prism'.\ntype Prism' s a = Prism s s a a\n\n-------------------------------------------------------------------------------\n-- Equality\n-------------------------------------------------------------------------------\n\n-- | A witness that @(a ~ s, b ~ t)@.\n--\n-- Note: Composition with an 'Equality' is index-preserving.\ntype Equality (s :: k1) (t :: k2) (a :: k1) (b :: k2) = forall k3 (p :: k1 -> k3 -> Type) (f :: k2 -> k3) .\n    p a (f b) -> p s (f t)\n\n-- | A 'Simple' 'Equality'.\ntype Equality' s a = Equality s s a a\n\n-- | Composable `asTypeOf`. Useful for constraining excess\n-- polymorphism, @foo . (id :: As Int) . bar@.\ntype As a = Equality' a a\n\n-------------------------------------------------------------------------------\n-- Getters\n-------------------------------------------------------------------------------\n\n-- | A 'Getter' describes how to retrieve a single value in a way that can be\n-- composed with other 'LensLike' constructions.\n--\n-- Unlike a 'Lens' a 'Getter' is read-only. Since a 'Getter'\n-- cannot be used to write back there are no 'Lens' laws that can be applied to\n-- it. In fact, it is isomorphic to an arbitrary function from @(s -> a)@.\n--\n-- Moreover, a 'Getter' can be used directly as a 'Control.Lens.Fold.Fold',\n-- since it just ignores the 'Applicative'.\ntype Getter s a = forall f. (Contravariant f, Functor f) => (a -> f a) -> s -> f s\n\n-- | Every 'IndexedGetter' is a valid 'Control.Lens.Fold.IndexedFold' and can be used for 'Control.Lens.Getter.Getting' like a 'Getter'.\ntype IndexedGetter i s a = forall p f. (Indexable i p, Contravariant f, Functor f) => p a (f a) -> s -> f s\n\n-- | An 'IndexPreservingGetter' can be used as a 'Getter', but when composed with an 'IndexedTraversal',\n-- 'IndexedFold', or 'IndexedLens' yields an 'IndexedFold', 'IndexedFold' or 'IndexedGetter' respectively.\ntype IndexPreservingGetter s a = forall p f. (Conjoined p, Contravariant f, Functor f) => p a (f a) -> p s (f s)\n\n--------------------------\n-- Folds\n--------------------------\n\n-- | A 'Fold' describes how to retrieve multiple values in a way that can be composed\n-- with other 'LensLike' constructions.\n--\n-- A @'Fold' s a@ provides a structure with operations very similar to those of the 'Data.Foldable.Foldable'\n-- typeclass, see 'Control.Lens.Fold.foldMapOf' and the other 'Fold' combinators.\n--\n-- By convention, if there exists a 'foo' method that expects a @'Data.Foldable.Foldable' (f a)@, then there should be a\n-- @fooOf@ method that takes a @'Fold' s a@ and a value of type @s@.\n--\n-- A 'Getter' is a legal 'Fold' that just ignores the supplied 'Data.Monoid.Monoid'.\n--\n-- Unlike a 'Control.Lens.Traversal.Traversal' a 'Fold' is read-only. Since a 'Fold' cannot be used to write back\n-- there are no 'Lens' laws that apply.\ntype Fold s a = forall f. (Contravariant f, Applicative f) => (a -> f a) -> s -> f s\n\n-- | Every 'IndexedFold' is a valid 'Control.Lens.Fold.Fold' and can be used for 'Control.Lens.Getter.Getting'.\ntype IndexedFold i s a = forall p f.  (Indexable i p, Contravariant f, Applicative f) => p a (f a) -> s -> f s\n\n-- | An 'IndexPreservingFold' can be used as a 'Fold', but when composed with an 'IndexedTraversal',\n-- 'IndexedFold', or 'IndexedLens' yields an 'IndexedFold' respectively.\ntype IndexPreservingFold s a = forall p f. (Conjoined p, Contravariant f, Applicative f) => p a (f a) -> p s (f s)\n\n-- | A relevant Fold (aka 'Fold1') has one or more targets.\ntype Fold1 s a = forall f. (Contravariant f, Apply f) => (a -> f a) -> s -> f s\ntype IndexedFold1 i s a = forall p f.  (Indexable i p, Contravariant f, Apply f) => p a (f a) -> s -> f s\ntype IndexPreservingFold1 s a = forall p f. (Conjoined p, Contravariant f, Apply f) => p a (f a) -> p s (f s)\n\n-------------------------------------------------------------------------------\n-- Simple Overloading\n-------------------------------------------------------------------------------\n\n-- | A 'Simple' 'Lens', 'Simple' 'Traversal', ... can\n-- be used instead of a 'Lens','Traversal', ...\n-- whenever the type variables don't change upon setting a value.\n--\n-- @\n-- 'Data.Complex.Lens._imagPart' :: 'Simple' 'Lens' ('Data.Complex.Complex' a) a\n-- 'Control.Lens.Traversal.traversed' :: 'Simple' ('IndexedTraversal' 'Int') [a] a\n-- @\n--\n-- Note: To use this alias in your own code with @'LensLike' f@ or\n-- 'Setter', you may have to turn on @LiberalTypeSynonyms@.\n--\n-- This is commonly abbreviated as a \\\"prime\\\" marker, /e.g./ 'Lens'' = 'Simple' 'Lens'.\ntype Simple f s a = f s s a a\n\n-------------------------------------------------------------------------------\n-- Optics\n-------------------------------------------------------------------------------\n\n-- | A valid 'Optic' @l@ should satisfy the laws:\n--\n-- @\n-- l 'pure' \u2261 'pure'\n-- l ('Procompose' f g) = 'Procompose' (l f) (l g)\n-- @\n--\n-- This gives rise to the laws for 'Equality', 'Iso', 'Prism', 'Lens',\n-- 'Traversal', 'Traversal1', 'Setter', 'Fold', 'Fold1', and 'Getter' as well\n-- along with their index-preserving variants.\n--\n-- @\n-- type 'LensLike' f s t a b = 'Optic' (->) f s t a b\n-- @\ntype Optic p f s t a b = p a (f b) -> p s (f t)\n\n-- | @\n-- type 'Optic'' p f s a = 'Simple' ('Optic' p f) s a\n-- @\ntype Optic' p f s a = Optic p f s s a a\n\n-- | @\n-- type 'LensLike' f s t a b = 'Optical' (->) (->) f s t a b\n-- @\n--\n-- @\n-- type 'Over' p f s t a b = 'Optical' p (->) f s t a b\n-- @\n--\n-- @\n-- type 'Optic' p f s t a b = 'Optical' p p f s t a b\n-- @\ntype Optical p q f s t a b = p a (f b) -> q s (f t)\n\n-- | @\n-- type 'Optical'' p q f s a = 'Simple' ('Optical' p q f) s a\n-- @\ntype Optical' p q f s a = Optical p q f s s a a\n\n\n-- | Many combinators that accept a 'Lens' can also accept a\n-- 'Traversal' in limited situations.\n--\n-- They do so by specializing the type of 'Functor' that they require of the\n-- caller.\n--\n-- If a function accepts a @'LensLike' f s t a b@ for some 'Functor' @f@,\n-- then they may be passed a 'Lens'.\n--\n-- Further, if @f@ is an 'Applicative', they may also be passed a\n-- 'Traversal'.\ntype LensLike f s t a b = (a -> f b) -> s -> f t\n\n-- | @\n-- type 'LensLike'' f = 'Simple' ('LensLike' f)\n-- @\ntype LensLike' f s a = LensLike f s s a a\n\n-- | Convenient alias for constructing indexed lenses and their ilk.\ntype IndexedLensLike i f s t a b = forall p. Indexable i p => p a (f b) -> s -> f t\n\n-- | Convenient alias for constructing simple indexed lenses and their ilk.\ntype IndexedLensLike' i f s a = IndexedLensLike i f s s a a\n\n-- | This is a convenient alias for use when you need to consume either indexed or non-indexed lens-likes based on context.\ntype Over p f s t a b = p a (f b) -> s -> f t\n\n-- | This is a convenient alias for use when you need to consume either indexed or non-indexed lens-likes based on context.\n--\n-- @\n-- type 'Over'' p f = 'Simple' ('Over' p f)\n-- @\ntype Over' p f s a = Over p f s s a a\n\n\n--------------------------\n-- Folds\n--------------------------\n\n-- | Obtain a 'Fold' by lifting an operation that returns a 'Foldable' result.\n--\n-- This can be useful to lift operations from @Data.List@ and elsewhere into a 'Fold'.\n--\n-- >>> [1,2,3,4]^..folding tail\n-- [2,3,4]\nfolding :: Foldable f => (s -> f a) -> Fold s a\nfolding sfa agb = phantom . traverse_ agb . sfa\n{-# INLINE folding #-}\n\nifolding :: (Foldable f, Indexable i p, Contravariant g, Applicative g) => (s -> f (i, a)) -> Over p g s t a b\nifolding sfa f = phantom . traverse_ (phantom . uncurry (indexed f)) . sfa\n{-# INLINE ifolding #-}\n\n-- | Obtain a 'Fold' by lifting 'foldr' like function.\n--\n-- >>> [1,2,3,4]^..foldring foldr\n-- [1,2,3,4]\nfoldring :: (Contravariant f, Applicative f) => ((a -> f a -> f a) -> f a -> s -> f a) -> LensLike f s t a b\nfoldring fr f = phantom . fr (\\a fa -> f a *> fa) noEffect\n{-# INLINE foldring #-}\n\n-- | Obtain 'FoldWithIndex' by lifting 'ifoldr' like function.\nifoldring :: (Indexable i p, Contravariant f, Applicative f) => ((i -> a -> f a -> f a) -> f a -> s -> f a) -> Over p f s t a b\nifoldring ifr f = phantom . ifr (\\i a fa -> indexed f i a *> fa) noEffect\n{-# INLINE ifoldring #-}\n\n-- | Obtain a 'Fold' from any 'Foldable' indexed by ordinal position.\n--\n-- >>> Just 3^..folded\n-- [3]\n--\n-- >>> Nothing^..folded\n-- []\n--\n-- >>> [(1,2),(3,4)]^..folded.both\n-- [1,2,3,4]\nfolded :: Foldable f => IndexedFold Int (f a) a\nfolded = conjoined (foldring foldr) (ifoldring ifoldr)\n{-# INLINE folded #-}\n\nifoldr :: Foldable f => (Int -> a -> b -> b) -> b -> f a -> b\nifoldr f z xs = foldr (\\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0\n{-# INLINE ifoldr #-}\n\n-- | Obtain a 'Fold' from any 'Foldable' indexed by ordinal position.\nfolded64 :: Foldable f => IndexedFold Int64 (f a) a\nfolded64 = conjoined (foldring foldr) (ifoldring ifoldr64)\n{-# INLINE folded64 #-}\n\nifoldr64 :: Foldable f => (Int64 -> a -> b -> b) -> b -> f a -> b\nifoldr64 f z xs = foldr (\\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0\n{-# INLINE ifoldr64 #-}\n\n-- | Form a 'Fold1' by repeating the input forever.\n--\n-- @\n-- 'repeat' \u2261 'toListOf' 'repeated'\n-- @\n--\n-- >>> timingOut $ 5^..taking 20 repeated\n-- [5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]\n--\n-- @\n-- 'repeated' :: 'Fold1' a a\n-- @\nrepeated :: Apply f => LensLike' f a a\nrepeated f a = as where as = f a .> as\n{-# INLINE repeated #-}\n\n-- | A 'Fold' that replicates its input @n@ times.\n--\n-- @\n-- 'replicate' n \u2261 'toListOf' ('replicated' n)\n-- @\n--\n-- >>> 5^..replicated 20\n-- [5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]\nreplicated :: Int -> Fold a a\nreplicated n0 f a = go n0 where\n  m = f a\n  go 0 = noEffect\n  go n = m *> go (n - 1)\n{-# INLINE replicated #-}\n\n-- | Transform a non-empty 'Fold' into a 'Fold1' that loops over its elements over and over.\n--\n-- >>> timingOut $ [1,2,3]^..taking 7 (cycled traverse)\n-- [1,2,3,1,2,3,1]\n--\n-- @\n-- 'cycled' :: 'Fold1' s a -> 'Fold1' s a\n-- @\ncycled :: Apply f => LensLike f s t a b -> LensLike f s t a b\ncycled l f a = as where as = l f a .> as\n{-# INLINE cycled #-}\n\n-- | Build a 'Fold' that unfolds its values from a seed.\n--\n-- @\n-- 'Prelude.unfoldr' \u2261 'toListOf' '.' 'unfolded'\n-- @\n--\n-- >>> 10^..unfolded (\\b -> if b == 0 then Nothing else Just (b, b-1))\n-- [10,9,8,7,6,5,4,3,2,1]\nunfolded :: (b -> Maybe (a, b)) -> Fold b a\nunfolded f g = go where\n  go b = case f b of\n    Just (a, b') -> g a *> go b'\n    Nothing      -> noEffect\n{-# INLINE unfolded #-}\n\n-- | @x '^.' 'iterated' f@ returns an infinite 'Fold1' of repeated applications of @f@ to @x@.\n--\n-- @\n-- 'toListOf' ('iterated' f) a \u2261 'iterate' f a\n-- @\n--\n-- @\n-- 'iterated' :: (a -> a) -> 'Fold1' a a\n-- @\niterated :: Apply f => (a -> a) -> LensLike' f a a\niterated f g = go where\n  go a = g a .> go (f a)\n{-# INLINE iterated #-}\n\n-- | Obtain a 'Fold' that can be composed with to filter another 'Lens', 'Iso', 'Getter', 'Fold' (or 'Traversal').\n--\n-- Note: This is /not/ a legal 'Traversal', unless you are very careful not to invalidate the predicate on the target.\n--\n-- Note: This is also /not/ a legal 'Prism', unless you are very careful not to inject a value that fails the predicate.\n--\n-- As a counter example, consider that given @evens = 'filtered' 'even'@ the second 'Traversal' law is violated:\n--\n-- @\n-- 'Control.Lens.Setter.over' evens 'succ' '.' 'Control.Lens.Setter.over' evens 'succ' '/=' 'Control.Lens.Setter.over' evens ('succ' '.' 'succ')\n-- @\n--\n-- So, in order for this to qualify as a legal 'Traversal' you can only use it for actions that preserve the result of the predicate!\n--\n-- >>> [1..10]^..folded.filtered even\n-- [2,4,6,8,10]\n--\n-- This will preserve an index if it is present.\nfiltered :: (Choice p, Applicative f) => (a -> Bool) -> Optic' p f a a\nfiltered p = dimap (\\x -> if p x then Right x else Left x) (either pure id) . right'\n{-# INLINE filtered #-}\n\n-- | Obtain a potentially empty 'IndexedTraversal' by taking the first element from another,\n-- potentially empty `Fold` and using it as an index.\n--\n-- The resulting optic can be composed with to filter another 'Lens', 'Iso', 'Getter', 'Fold' (or 'Traversal').\n--\n-- >>> [(Just 2, 3), (Nothing, 4)] & mapped . filteredBy (_1 . _Just) <. _2 %@~ (*) :: [(Maybe Int, Int)]\n-- [(Just 2,6),(Nothing,4)]\n--\n-- @\n-- 'filteredBy' :: 'Fold' a i -> 'IndexedTraversal'' i a a\n-- @\n--\n-- Note: As with 'filtered', this is /not/ a legal 'IndexedTraversal', unless you are very careful not to invalidate the predicate on the target!\nfilteredBy :: (Indexable i p, Applicative f) => Getting (First i) a i -> p a (f a) -> a -> f a\nfilteredBy p f val = case val ^? p of\n  Nothing -> pure val\n  Just witness -> indexed f witness val\n\n-- | Obtain a 'Fold' by taking elements from another 'Fold', 'Lens', 'Iso', 'Getter' or 'Traversal' while a predicate holds.\n--\n-- @\n-- 'takeWhile' p \u2261 'toListOf' ('takingWhile' p 'folded')\n-- @\n--\n-- >>> timingOut $ toListOf (takingWhile (<=3) folded) [1..]\n-- [1,2,3]\n--\n-- @\n-- 'takingWhile' :: (a -> 'Bool') -> 'Fold' s a                         -> 'Fold' s a\n-- 'takingWhile' :: (a -> 'Bool') -> 'Getter' s a                       -> 'Fold' s a\n-- 'takingWhile' :: (a -> 'Bool') -> 'Traversal'' s a                   -> 'Fold' s a -- * See note below\n-- 'takingWhile' :: (a -> 'Bool') -> 'Lens'' s a                        -> 'Fold' s a -- * See note below\n-- 'takingWhile' :: (a -> 'Bool') -> 'Prism'' s a                       -> 'Fold' s a -- * See note below\n-- 'takingWhile' :: (a -> 'Bool') -> 'Iso'' s a                         -> 'Fold' s a -- * See note below\n-- 'takingWhile' :: (a -> 'Bool') -> 'IndexedTraversal'' i s a          -> 'IndexedFold' i s a -- * See note below\n-- 'takingWhile' :: (a -> 'Bool') -> 'IndexedLens'' i s a               -> 'IndexedFold' i s a -- * See note below\n-- 'takingWhile' :: (a -> 'Bool') -> 'IndexedFold' i s a                -> 'IndexedFold' i s a\n-- 'takingWhile' :: (a -> 'Bool') -> 'IndexedGetter' i s a              -> 'IndexedFold' i s a\n-- @\n--\n-- /Note:/ When applied to a 'Traversal', 'takingWhile' yields something that can be used as if it were a 'Traversal', but\n-- which is not a 'Traversal' per the laws, unless you are careful to ensure that you do not invalidate the predicate when\n-- writing back through it.\ntakingWhile :: (Conjoined p, Applicative f) => (a -> Bool) -> Over p (TakingWhile p f a a) s t a a -> Over p f s t a a\ntakingWhile p l pafb = fmap runMagma . traverse (cosieve pafb) . runTakingWhile . l flag where\n  flag = cotabulate $ \\wa -> let a = extract wa; r = p a in TakingWhile r a $ \\pr ->\n    if pr && r then Magma () wa else MagmaPure a\n{-# INLINE takingWhile #-}\n\n-- | Obtain a 'Fold' by dropping elements from another 'Fold', 'Lens', 'Iso', 'Getter' or 'Traversal' while a predicate holds.\n--\n-- @\n-- 'dropWhile' p \u2261 'toListOf' ('droppingWhile' p 'folded')\n-- @\n--\n-- >>> toListOf (droppingWhile (<=3) folded) [1..6]\n-- [4,5,6]\n--\n-- >>> toListOf (droppingWhile (<=3) folded) [1,6,1]\n-- [6,1]\n--\n-- @\n-- 'droppingWhile' :: (a -> 'Bool') -> 'Fold' s a                         -> 'Fold' s a\n-- 'droppingWhile' :: (a -> 'Bool') -> 'Getter' s a                       -> 'Fold' s a\n-- 'droppingWhile' :: (a -> 'Bool') -> 'Traversal'' s a                   -> 'Fold' s a                -- see notes\n-- 'droppingWhile' :: (a -> 'Bool') -> 'Lens'' s a                        -> 'Fold' s a                -- see notes\n-- 'droppingWhile' :: (a -> 'Bool') -> 'Prism'' s a                       -> 'Fold' s a                -- see notes\n-- 'droppingWhile' :: (a -> 'Bool') -> 'Iso'' s a                         -> 'Fold' s a                -- see notes\n-- @\n--\n-- @\n-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexPreservingTraversal'' s a    -> 'IndexPreservingFold' s a -- see notes\n-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexPreservingLens'' s a         -> 'IndexPreservingFold' s a -- see notes\n-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexPreservingGetter' s a        -> 'IndexPreservingFold' s a\n-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexPreservingFold' s a          -> 'IndexPreservingFold' s a\n-- @\n--\n-- @\n-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexedTraversal'' i s a          -> 'IndexedFold' i s a       -- see notes\n-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexedLens'' i s a               -> 'IndexedFold' i s a       -- see notes\n-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexedGetter' i s a              -> 'IndexedFold' i s a\n-- 'droppingWhile' :: (a -> 'Bool') -> 'IndexedFold' i s a                -> 'IndexedFold' i s a\n-- @\n--\n-- Note: Many uses of this combinator will yield something that meets the types, but not the laws of a valid\n-- 'Traversal' or 'IndexedTraversal'. The 'Traversal' and 'IndexedTraversal' laws are only satisfied if the\n-- new values you assign to the first target also does not pass the predicate! Otherwise subsequent traversals\n-- will visit fewer elements and 'Traversal' fusion is not sound.\n--\n-- So for any traversal @t@ and predicate @p@, @`droppingWhile` p t@ may not be lawful, but\n-- @(`Control.Lens.Traversal.dropping` 1 . `droppingWhile` p) t@ is. For example:\n--\n-- >>> let l  :: Traversal' [Int] Int; l  = droppingWhile (<= 1) traverse\n-- >>> let l' :: Traversal' [Int] Int; l' = dropping 1 l\n--\n-- @l@ is not a lawful setter because @`Control.Lens.Setter.over` l f .\n-- `Control.Lens.Setter.over` l g \u2262 `Control.Lens.Setter.over` l (f . g)@:\n--\n-- >>> [1,2,3] & l .~ 0 & l .~ 4\n-- [1,0,0]\n-- >>> [1,2,3] & l .~ 4\n-- [1,4,4]\n--\n-- @l'@ on the other hand behaves lawfully:\n--\n-- >>> [1,2,3] & l' .~ 0 & l' .~ 4\n-- [1,2,4]\n-- >>> [1,2,3] & l' .~ 4\n-- [1,2,4]\ndroppingWhile :: (Conjoined p, Profunctor q, Applicative f)\n              => (a -> Bool)\n              -> Optical p q (Compose (State Bool) f) s t a a\n              -> Optical p q f s t a a\ndroppingWhile p l f = (flip evalState True .# getCompose) `rmap` l g where\n  g = cotabulate $ \\wa -> Compose $ state $ \\b -> let\n      a = extract wa\n      b' = b && p a\n    in (if b' then pure a else cosieve f wa, b')\n{-# INLINE droppingWhile #-}\n\n-- | A 'Fold' over the individual 'words' of a 'String'.\n--\n-- @\n-- 'worded' :: 'Fold' 'String' 'String'\n-- 'worded' :: 'Traversal'' 'String' 'String'\n-- @\n--\n-- @\n-- 'worded' :: 'IndexedFold' 'Int' 'String' 'String'\n-- 'worded' :: 'IndexedTraversal'' 'Int' 'String' 'String'\n-- @\n--\n-- Note: This function type-checks as a 'Traversal' but it doesn't satisfy the laws. It's only valid to use it\n-- when you don't insert any whitespace characters while traversing, and if your original 'String' contains only\n-- isolated space characters (and no other characters that count as space, such as non-breaking spaces).\nworded :: Applicative f => IndexedLensLike' Int f String String\nworded f = fmap unwords . conjoined traverse (indexing traverse) f . words\n{-# INLINE worded #-}\n\n-- | A 'Fold' over the individual 'lines' of a 'String'.\n--\n-- @\n-- 'lined' :: 'Fold' 'String' 'String'\n-- 'lined' :: 'Traversal'' 'String' 'String'\n-- @\n--\n-- @\n-- 'lined' :: 'IndexedFold' 'Int' 'String' 'String'\n-- 'lined' :: 'IndexedTraversal'' 'Int' 'String' 'String'\n-- @\n--\n-- Note: This function type-checks as a 'Traversal' but it doesn't satisfy the laws. It's only valid to use it\n-- when you don't insert any newline characters while traversing, and if your original 'String' contains only\n-- isolated newline characters.\nlined :: Applicative f => IndexedLensLike' Int f String String\nlined f = fmap (intercalate \"\\n\") . conjoined traverse (indexing traverse) f . lines\n{-# INLINE lined #-}\n\n--------------------------\n-- Fold/Getter combinators\n--------------------------\n\n-- | Map each part of a structure viewed through a 'Lens', 'Getter',\n-- 'Fold' or 'Traversal' to a monoid and combine the results.\n--\n-- >>> foldMapOf (folded . both . _Just) Sum [(Just 21, Just 21)]\n-- Sum {getSum = 42}\n--\n-- @\n-- 'Data.Foldable.foldMap' = 'foldMapOf' 'folded'\n-- @\n--\n-- @\n-- 'foldMapOf' \u2261 'views'\n-- 'ifoldMapOf' l = 'foldMapOf' l '.' 'Indexed'\n-- @\n--\n-- @\n-- 'foldMapOf' ::                'Getter' s a      -> (a -> r) -> s -> r\n-- 'foldMapOf' :: 'Monoid' r    => 'Fold' s a        -> (a -> r) -> s -> r\n-- 'foldMapOf' :: 'Semigroup' r => 'Fold1' s a       -> (a -> r) -> s -> r\n-- 'foldMapOf' ::                'Lens'' s a       -> (a -> r) -> s -> r\n-- 'foldMapOf' ::                'Iso'' s a        -> (a -> r) -> s -> r\n-- 'foldMapOf' :: 'Monoid' r    => 'Traversal'' s a  -> (a -> r) -> s -> r\n-- 'foldMapOf' :: 'Semigroup' r => 'Traversal1'' s a -> (a -> r) -> s -> r\n-- 'foldMapOf' :: 'Monoid' r    => 'Prism'' s a      -> (a -> r) -> s -> r\n-- @\n--\n-- @\n-- 'foldMapOf' :: 'Getting' r s a -> (a -> r) -> s -> r\n-- @\nfoldMapOf :: Getting r s a -> (a -> r) -> s -> r\nfoldMapOf = coerce\n{-# INLINE foldMapOf #-}\n\n-- | Combine the elements of a structure viewed through a 'Lens', 'Getter',\n-- 'Fold' or 'Traversal' using a monoid.\n--\n-- >>> foldOf (folded.folded) [[Sum 1,Sum 4],[Sum 8, Sum 8],[Sum 21]]\n-- Sum {getSum = 42}\n--\n-- @\n-- 'Data.Foldable.fold' = 'foldOf' 'folded'\n-- @\n--\n-- @\n-- 'foldOf' \u2261 'view'\n-- @\n--\n-- @\n-- 'foldOf' ::             'Getter' s m     -> s -> m\n-- 'foldOf' :: 'Monoid' m => 'Fold' s m       -> s -> m\n-- 'foldOf' ::             'Lens'' s m      -> s -> m\n-- 'foldOf' ::             'Iso'' s m       -> s -> m\n-- 'foldOf' :: 'Monoid' m => 'Traversal'' s m -> s -> m\n-- 'foldOf' :: 'Monoid' m => 'Prism'' s m     -> s -> m\n-- @\nfoldOf :: Getting a s a -> s -> a\nfoldOf l = getConst #. l Const\n{-# INLINE foldOf #-}\n\n-- | Right-associative fold of parts of a structure that are viewed through a 'Lens', 'Getter', 'Fold' or 'Traversal'.\n--\n-- @\n-- 'Data.Foldable.foldr' \u2261 'foldrOf' 'folded'\n-- @\n--\n-- @\n-- 'foldrOf' :: 'Getter' s a     -> (a -> r -> r) -> r -> s -> r\n-- 'foldrOf' :: 'Fold' s a       -> (a -> r -> r) -> r -> s -> r\n-- 'foldrOf' :: 'Lens'' s a      -> (a -> r -> r) -> r -> s -> r\n-- 'foldrOf' :: 'Iso'' s a       -> (a -> r -> r) -> r -> s -> r\n-- 'foldrOf' :: 'Traversal'' s a -> (a -> r -> r) -> r -> s -> r\n-- 'foldrOf' :: 'Prism'' s a     -> (a -> r -> r) -> r -> s -> r\n-- @\n--\n-- @\n-- 'ifoldrOf' l \u2261 'foldrOf' l '.' 'Indexed'\n-- @\n--\n-- @\n-- 'foldrOf' :: 'Getting' ('Endo' r) s a -> (a -> r -> r) -> r -> s -> r\n-- @\nfoldrOf :: Getting (Endo r) s a -> (a -> r -> r) -> r -> s -> r\nfoldrOf l f z = flip appEndo z . foldMapOf l (Endo #. f)\n{-# INLINE foldrOf #-}\n\n-- | Left-associative fold of the parts of a structure that are viewed through a 'Lens', 'Getter', 'Fold' or 'Traversal'.\n--\n-- @\n-- 'Data.Foldable.foldl' \u2261 'foldlOf' 'folded'\n-- @\n--\n-- @\n-- 'foldlOf' :: 'Getter' s a     -> (r -> a -> r) -> r -> s -> r\n-- 'foldlOf' :: 'Fold' s a       -> (r -> a -> r) -> r -> s -> r\n-- 'foldlOf' :: 'Lens'' s a      -> (r -> a -> r) -> r -> s -> r\n-- 'foldlOf' :: 'Iso'' s a       -> (r -> a -> r) -> r -> s -> r\n-- 'foldlOf' :: 'Traversal'' s a -> (r -> a -> r) -> r -> s -> r\n-- 'foldlOf' :: 'Prism'' s a     -> (r -> a -> r) -> r -> s -> r\n-- @\nfoldlOf :: Getting (Dual (Endo r)) s a -> (r -> a -> r) -> r -> s -> r\nfoldlOf l f z = (flip appEndo z .# getDual) `rmap` foldMapOf l (Dual #. Endo #. flip f)\n{-# INLINE foldlOf #-}\n\n-- | Extract a list of the targets of a 'Fold'. See also ('^..').\n--\n-- @\n-- 'Data.Foldable.toList' \u2261 'toListOf' 'folded'\n-- ('^..') \u2261 'flip' 'toListOf'\n-- @\n\n-- >>> toListOf both (\"hello\",\"world\")\n-- [\"hello\",\"world\"]\n--\n-- @\n-- 'toListOf' :: 'Getter' s a     -> s -> [a]\n-- 'toListOf' :: 'Fold' s a       -> s -> [a]\n-- 'toListOf' :: 'Lens'' s a      -> s -> [a]\n-- 'toListOf' :: 'Iso'' s a       -> s -> [a]\n-- 'toListOf' :: 'Traversal'' s a -> s -> [a]\n-- 'toListOf' :: 'Prism'' s a     -> s -> [a]\n-- @\ntoListOf :: Getting (Endo [a]) s a -> s -> [a]\ntoListOf l = foldrOf l (:) []\n{-# INLINE toListOf #-}\n\n-- | Extract a 'NonEmpty' of the targets of 'Fold1'.\n--\n-- >>> toNonEmptyOf both1 (\"hello\", \"world\")\n-- \"hello\" :| [\"world\"]\n--\n-- @\n-- 'toNonEmptyOf' :: 'Getter' s a      -> s -> NonEmpty a\n-- 'toNonEmptyOf' :: 'Fold1' s a       -> s -> NonEmpty a\n-- 'toNonEmptyOf' :: 'Lens'' s a       -> s -> NonEmpty a\n-- 'toNonEmptyOf' :: 'Iso'' s a        -> s -> NonEmpty a\n-- 'toNonEmptyOf' :: 'Traversal1'' s a -> s -> NonEmpty a\n-- 'toNonEmptyOf' :: 'Prism'' s a      -> s -> NonEmpty a\n-- @\ntoNonEmptyOf :: Getting (NonEmptyDList a) s a -> s -> NonEmpty a\ntoNonEmptyOf l = flip getNonEmptyDList [] . foldMapOf l (NonEmptyDList #. (:|))\n\n-- | A convenient infix (flipped) version of 'toListOf'.\n--\n-- >>> [[1,2],[3]]^..id\n-- [[[1,2],[3]]]\n-- >>> [[1,2],[3]]^..traverse\n-- [[1,2],[3]]\n-- >>> [[1,2],[3]]^..traverse.traverse\n-- [1,2,3]\n--\n-- >>> (1,2)^..both\n-- [1,2]\n--\n-- @\n-- 'Data.Foldable.toList' xs \u2261 xs '^..' 'folded'\n-- ('^..') \u2261 'flip' 'toListOf'\n-- @\n--\n-- @\n-- ('^..') :: s -> 'Getter' s a     -> [a]\n-- ('^..') :: s -> 'Fold' s a       -> [a]\n-- ('^..') :: s -> 'Lens'' s a      -> [a]\n-- ('^..') :: s -> 'Iso'' s a       -> [a]\n-- ('^..') :: s -> 'Traversal'' s a -> [a]\n-- ('^..') :: s -> 'Prism'' s a     -> [a]\n-- @\n(^..) :: s -> Getting (Endo [a]) s a -> [a]\ns ^.. l = toListOf l s\n{-# INLINE (^..) #-}\n\n-- | Returns 'True' if every target of a 'Fold' is 'True'.\n--\n-- >>> andOf both (True,False)\n-- False\n-- >>> andOf both (True,True)\n-- True\n--\n-- @\n-- 'Data.Foldable.and' \u2261 'andOf' 'folded'\n-- @\n--\n-- @\n-- 'andOf' :: 'Getter' s 'Bool'     -> s -> 'Bool'\n-- 'andOf' :: 'Fold' s 'Bool'       -> s -> 'Bool'\n-- 'andOf' :: 'Lens'' s 'Bool'      -> s -> 'Bool'\n-- 'andOf' :: 'Iso'' s 'Bool'       -> s -> 'Bool'\n-- 'andOf' :: 'Traversal'' s 'Bool' -> s -> 'Bool'\n-- 'andOf' :: 'Prism'' s 'Bool'     -> s -> 'Bool'\n-- @\nandOf :: Getting All s Bool -> s -> Bool\nandOf l = getAll #. foldMapOf l All\n{-# INLINE andOf #-}\n\n-- | Returns 'True' if any target of a 'Fold' is 'True'.\n--\n-- >>> orOf both (True,False)\n-- True\n-- >>> orOf both (False,False)\n-- False\n--\n-- @\n-- 'Data.Foldable.or' \u2261 'orOf' 'folded'\n-- @\n--\n-- @\n-- 'orOf' :: 'Getter' s 'Bool'     -> s -> 'Bool'\n-- 'orOf' :: 'Fold' s 'Bool'       -> s -> 'Bool'\n-- 'orOf' :: 'Lens'' s 'Bool'      -> s -> 'Bool'\n-- 'orOf' :: 'Iso'' s 'Bool'       -> s -> 'Bool'\n-- 'orOf' :: 'Traversal'' s 'Bool' -> s -> 'Bool'\n-- 'orOf' :: 'Prism'' s 'Bool'     -> s -> 'Bool'\n-- @\norOf :: Getting Any s Bool -> s -> Bool\norOf l = getAny #. foldMapOf l Any\n{-# INLINE orOf #-}\n\n-- | Returns 'True' if any target of a 'Fold' satisfies a predicate.\n--\n-- >>> anyOf both (=='x') ('x','y')\n-- True\n-- >>> import Data.Data.Lens\n-- >>> anyOf biplate (== \"world\") (((),2::Int),\"hello\",(\"world\",11::Int))\n-- True\n--\n-- @\n-- 'Data.Foldable.any' \u2261 'anyOf' 'folded'\n-- @\n--\n-- @\n-- 'ianyOf' l \u2261 'anyOf' l '.' 'Indexed'\n-- @\n--\n-- @\n-- 'anyOf' :: 'Getter' s a     -> (a -> 'Bool') -> s -> 'Bool'\n-- 'anyOf' :: 'Fold' s a       -> (a -> 'Bool') -> s -> 'Bool'\n-- 'anyOf' :: 'Lens'' s a      -> (a -> 'Bool') -> s -> 'Bool'\n-- 'anyOf' :: 'Iso'' s a       -> (a -> 'Bool') -> s -> 'Bool'\n-- 'anyOf' :: 'Traversal'' s a -> (a -> 'Bool') -> s -> 'Bool'\n-- 'anyOf' :: 'Prism'' s a     -> (a -> 'Bool') -> s -> 'Bool'\n-- @\nanyOf :: Getting Any s a -> (a -> Bool) -> s -> Bool\nanyOf l f = getAny #. foldMapOf l (Any #. f)\n{-# INLINE anyOf #-}\n\n-- | Returns 'True' if every target of a 'Fold' satisfies a predicate.\n--\n-- >>> allOf both (>=3) (4,5)\n-- True\n-- >>> allOf folded (>=2) [1..10]\n-- False\n--\n-- @\n-- 'Data.Foldable.all' \u2261 'allOf' 'folded'\n-- @\n--\n-- @\n-- 'iallOf' l = 'allOf' l '.' 'Indexed'\n-- @\n--\n-- @\n-- 'allOf' :: 'Getter' s a     -> (a -> 'Bool') -> s -> 'Bool'\n-- 'allOf' :: 'Fold' s a       -> (a -> 'Bool') -> s -> 'Bool'\n-- 'allOf' :: 'Lens'' s a      -> (a -> 'Bool') -> s -> 'Bool'\n-- 'allOf' :: 'Iso'' s a       -> (a -> 'Bool') -> s -> 'Bool'\n-- 'allOf' :: 'Traversal'' s a -> (a -> 'Bool') -> s -> 'Bool'\n-- 'allOf' :: 'Prism'' s a     -> (a -> 'Bool') -> s -> 'Bool'\n-- @\nallOf :: Getting All s a -> (a -> Bool) -> s -> Bool\nallOf l f = getAll #. foldMapOf l (All #. f)\n{-# INLINE allOf #-}\n\n-- | Returns 'True' only if no targets of a 'Fold' satisfy a predicate.\n--\n-- >>> noneOf each (is _Nothing) (Just 3, Just 4, Just 5)\n-- True\n-- >>> noneOf (folded.folded) (<10) [[13,99,20],[3,71,42]]\n-- False\n--\n-- @\n-- 'inoneOf' l = 'noneOf' l '.' 'Indexed'\n-- @\n--\n-- @\n-- 'noneOf' :: 'Getter' s a     -> (a -> 'Bool') -> s -> 'Bool'\n-- 'noneOf' :: 'Fold' s a       -> (a -> 'Bool') -> s -> 'Bool'\n-- 'noneOf' :: 'Lens'' s a      -> (a -> 'Bool') -> s -> 'Bool'\n-- 'noneOf' :: 'Iso'' s a       -> (a -> 'Bool') -> s -> 'Bool'\n-- 'noneOf' :: 'Traversal'' s a -> (a -> 'Bool') -> s -> 'Bool'\n-- 'noneOf' :: 'Prism'' s a     -> (a -> 'Bool') -> s -> 'Bool'\n-- @\nnoneOf :: Getting Any s a -> (a -> Bool) -> s -> Bool\nnoneOf l f = not . anyOf l f\n{-# INLINE noneOf #-}\n\n-- | Calculate the 'Product' of every number targeted by a 'Fold'.\n--\n-- >>> productOf both (4,5)\n-- 20\n-- >>> productOf folded [1,2,3,4,5]\n-- 120\n--\n-- @\n-- 'Data.Foldable.product' \u2261 'productOf' 'folded'\n-- @\n--\n-- This operation may be more strict than you would expect. If you\n-- want a lazier version use @'ala' 'Product' '.' 'foldMapOf'@\n--\n-- @\n-- 'productOf' :: 'Num' a => 'Getter' s a     -> s -> a\n-- 'productOf' :: 'Num' a => 'Fold' s a       -> s -> a\n-- 'productOf' :: 'Num' a => 'Lens'' s a      -> s -> a\n-- 'productOf' :: 'Num' a => 'Iso'' s a       -> s -> a\n-- 'productOf' :: 'Num' a => 'Traversal'' s a -> s -> a\n-- 'productOf' :: 'Num' a => 'Prism'' s a     -> s -> a\n-- @\nproductOf :: Num a => Getting (Endo (Endo a)) s a -> s -> a\nproductOf l = foldlOf' l (*) 1\n{-# INLINE productOf #-}\n\n-- | Calculate the 'Sum' of every number targeted by a 'Fold'.\n--\n-- >>> sumOf both (5,6)\n-- 11\n-- >>> sumOf folded [1,2,3,4]\n-- 10\n-- >>> sumOf (folded.both) [(1,2),(3,4)]\n-- 10\n-- >>> import Data.Data.Lens\n-- >>> sumOf biplate [(1::Int,[]),(2,[(3::Int,4::Int)])] :: Int\n-- 10\n--\n-- @\n-- 'Data.Foldable.sum' \u2261 'sumOf' 'folded'\n-- @\n--\n-- This operation may be more strict than you would expect. If you\n-- want a lazier version use @'ala' 'Sum' '.' 'foldMapOf'@\n--\n-- @\n-- 'sumOf' '_1' :: 'Num' a => (a, b) -> a\n-- 'sumOf' ('folded' '.' 'Control.Lens.Tuple._1') :: ('Foldable' f, 'Num' a) => f (a, b) -> a\n-- @\n--\n-- @\n-- 'sumOf' :: 'Num' a => 'Getter' s a     -> s -> a\n-- 'sumOf' :: 'Num' a => 'Fold' s a       -> s -> a\n-- 'sumOf' :: 'Num' a => 'Lens'' s a      -> s -> a\n-- 'sumOf' :: 'Num' a => 'Iso'' s a       -> s -> a\n-- 'sumOf' :: 'Num' a => 'Traversal'' s a -> s -> a\n-- 'sumOf' :: 'Num' a => 'Prism'' s a     -> s -> a\n-- @\nsumOf :: Num a => Getting (Endo (Endo a)) s a -> s -> a\nsumOf l = foldlOf' l (+) 0\n{-# INLINE sumOf #-}\n\n-- | Traverse over all of the targets of a 'Fold' (or 'Getter'), computing an 'Applicative' (or 'Functor')-based answer,\n-- but unlike 'Control.Lens.Traversal.traverseOf' do not construct a new structure. 'traverseOf_' generalizes\n-- 'Data.Foldable.traverse_' to work over any 'Fold'.\n--\n-- When passed a 'Getter', 'traverseOf_' can work over any 'Functor', but when passed a 'Fold', 'traverseOf_' requires\n-- an 'Applicative'.\n--\n-- >>> traverseOf_ both putStrLn (\"hello\",\"world\")\n-- hello\n-- world\n--\n-- @\n-- 'Data.Foldable.traverse_' \u2261 'traverseOf_' 'folded'\n-- @\n--\n-- @\n-- 'traverseOf_' '_2' :: 'Functor' f => (c -> f r) -> (d, c) -> f ()\n-- 'traverseOf_' 'Control.Lens.Prism._Left' :: 'Applicative' f => (a -> f b) -> 'Either' a c -> f ()\n-- @\n--\n-- @\n-- 'itraverseOf_' l \u2261 'traverseOf_' l '.' 'Indexed'\n-- @\n--\n-- The rather specific signature of 'traverseOf_' allows it to be used as if the signature was any of:\n--\n-- @\n-- 'traverseOf_' :: 'Functor' f     => 'Getter' s a     -> (a -> f r) -> s -> f ()\n-- 'traverseOf_' :: 'Applicative' f => 'Fold' s a       -> (a -> f r) -> s -> f ()\n-- 'traverseOf_' :: 'Functor' f     => 'Lens'' s a      -> (a -> f r) -> s -> f ()\n-- 'traverseOf_' :: 'Functor' f     => 'Iso'' s a       -> (a -> f r) -> s -> f ()\n-- 'traverseOf_' :: 'Applicative' f => 'Traversal'' s a -> (a -> f r) -> s -> f ()\n-- 'traverseOf_' :: 'Applicative' f => 'Prism'' s a     -> (a -> f r) -> s -> f ()\n-- @\ntraverseOf_ :: Functor f => Getting (Traversed r f) s a -> (a -> f r) -> s -> f ()\ntraverseOf_ l f = void . getTraversed #. foldMapOf l (Traversed #. f)\n{-# INLINE traverseOf_ #-}\n\n-- | Traverse over all of the targets of a 'Fold' (or 'Getter'), computing an 'Applicative' (or 'Functor')-based answer,\n-- but unlike 'Control.Lens.Traversal.forOf' do not construct a new structure. 'forOf_' generalizes\n-- 'Data.Foldable.for_' to work over any 'Fold'.\n--\n-- When passed a 'Getter', 'forOf_' can work over any 'Functor', but when passed a 'Fold', 'forOf_' requires\n-- an 'Applicative'.\n--\n-- @\n-- 'for_' \u2261 'forOf_' 'folded'\n-- @\n--\n-- >>> forOf_ both (\"hello\",\"world\") putStrLn\n-- hello\n-- world\n--\n-- The rather specific signature of 'forOf_' allows it to be used as if the signature was any of:\n--\n-- @\n-- 'iforOf_' l s \u2261 'forOf_' l s '.' 'Indexed'\n-- @\n--\n-- @\n-- 'forOf_' :: 'Functor' f     => 'Getter' s a     -> s -> (a -> f r) -> f ()\n-- 'forOf_' :: 'Applicative' f => 'Fold' s a       -> s -> (a -> f r) -> f ()\n-- 'forOf_' :: 'Functor' f     => 'Lens'' s a      -> s -> (a -> f r) -> f ()\n-- 'forOf_' :: 'Functor' f     => 'Iso'' s a       -> s -> (a -> f r) -> f ()\n-- 'forOf_' :: 'Applicative' f => 'Traversal'' s a -> s -> (a -> f r) -> f ()\n-- 'forOf_' :: 'Applicative' f => 'Prism'' s a     -> s -> (a -> f r) -> f ()\n-- @\nforOf_ :: Functor f => Getting (Traversed r f) s a -> s -> (a -> f r) -> f ()\nforOf_ = flip . traverseOf_\n{-# INLINE forOf_ #-}\n\n-- | Evaluate each action in observed by a 'Fold' on a structure from left to right, ignoring the results.\n--\n-- @\n-- 'sequenceA_' \u2261 'sequenceAOf_' 'folded'\n-- @\n--\n-- >>> sequenceAOf_ both (putStrLn \"hello\",putStrLn \"world\")\n-- hello\n-- world\n--\n-- @\n-- 'sequenceAOf_' :: 'Functor' f     => 'Getter' s (f a)     -> s -> f ()\n-- 'sequenceAOf_' :: 'Applicative' f => 'Fold' s (f a)       -> s -> f ()\n-- 'sequenceAOf_' :: 'Functor' f     => 'Lens'' s (f a)      -> s -> f ()\n-- 'sequenceAOf_' :: 'Functor' f     => 'Iso'' s (f a)       -> s -> f ()\n-- 'sequenceAOf_' :: 'Applicative' f => 'Traversal'' s (f a) -> s -> f ()\n-- 'sequenceAOf_' :: 'Applicative' f => 'Prism'' s (f a)     -> s -> f ()\n-- @\nsequenceAOf_ :: Functor f => Getting (Traversed a f) s (f a) -> s -> f ()\nsequenceAOf_ l = void . getTraversed #. foldMapOf l Traversed\n{-# INLINE sequenceAOf_ #-}\n\n-- | Traverse over all of the targets of a 'Fold1', computing an 'Apply' based answer.\n--\n-- As long as you have 'Applicative' or 'Functor' effect you are better using 'traverseOf_'.\n-- The 'traverse1Of_' is useful only when you have genuine 'Apply' effect.\n--\n-- >>> traverse1Of_ both1 (\\ks -> Map.fromList [ (k, ()) | k <- ks ]) (\"abc\", \"bcd\")\n-- fromList [('b',()),('c',())]\n--\n-- @\n-- 'traverse1Of_' :: 'Apply' f => 'Fold1' s a -> (a -> f r) -> s -> f ()\n-- @\n--\n-- @since 4.16\ntraverse1Of_ :: Functor f => Getting (TraversedF r f) s a -> (a -> f r) -> s -> f ()\ntraverse1Of_ l f = void . getTraversedF #. foldMapOf l (TraversedF #. f)\n{-# INLINE traverse1Of_ #-}\n\n-- | See 'forOf_' and 'traverse1Of_'.\n--\n-- >>> for1Of_ both1 (\"abc\", \"bcd\") (\\ks -> Map.fromList [ (k, ()) | k <- ks ])\n-- fromList [('b',()),('c',())]\n--\n-- @\n-- 'for1Of_' :: 'Apply' f => 'Fold1' s a -> s -> (a -> f r) -> f ()\n-- @\n--\n-- @since 4.16\nfor1Of_ :: Functor f => Getting (TraversedF r f) s a -> s -> (a -> f r) -> f ()\nfor1Of_ = flip . traverse1Of_\n{-# INLINE for1Of_ #-}\n\n-- | See 'sequenceAOf_' and 'traverse1Of_'.\n--\n-- @\n-- 'sequence1Of_' :: 'Apply' f => 'Fold1' s (f a) -> s -> f ()\n-- @\n--\n-- @since 4.16\nsequence1Of_ :: Functor f => Getting (TraversedF a f) s (f a) -> s -> f ()\nsequence1Of_ l = void . getTraversedF #. foldMapOf l TraversedF\n{-# INLINE sequence1Of_ #-}\n\n-- | Map each target of a 'Fold' on a structure to a monadic action, evaluate these actions from left to right, and ignore the results.\n--\n-- >>> mapMOf_ both putStrLn (\"hello\",\"world\")\n-- hello\n-- world\n--\n-- @\n-- 'Data.Foldable.mapM_' \u2261 'mapMOf_' 'folded'\n-- @\n--\n-- @\n-- 'mapMOf_' :: 'Monad' m => 'Getter' s a     -> (a -> m r) -> s -> m ()\n-- 'mapMOf_' :: 'Monad' m => 'Fold' s a       -> (a -> m r) -> s -> m ()\n-- 'mapMOf_' :: 'Monad' m => 'Lens'' s a      -> (a -> m r) -> s -> m ()\n-- 'mapMOf_' :: 'Monad' m => 'Iso'' s a       -> (a -> m r) -> s -> m ()\n-- 'mapMOf_' :: 'Monad' m => 'Traversal'' s a -> (a -> m r) -> s -> m ()\n-- 'mapMOf_' :: 'Monad' m => 'Prism'' s a     -> (a -> m r) -> s -> m ()\n-- @\nmapMOf_ :: Monad m => Getting (Sequenced r m) s a -> (a -> m r) -> s -> m ()\nmapMOf_ l f = liftM skip . getSequenced #. foldMapOf l (Sequenced #. f)\n{-# INLINE mapMOf_ #-}\n\n-- | 'forMOf_' is 'mapMOf_' with two of its arguments flipped.\n--\n-- >>> forMOf_ both (\"hello\",\"world\") putStrLn\n-- hello\n-- world\n--\n-- @\n-- 'Data.Foldable.forM_' \u2261 'forMOf_' 'folded'\n-- @\n--\n-- @\n-- 'forMOf_' :: 'Monad' m => 'Getter' s a     -> s -> (a -> m r) -> m ()\n-- 'forMOf_' :: 'Monad' m => 'Fold' s a       -> s -> (a -> m r) -> m ()\n-- 'forMOf_' :: 'Monad' m => 'Lens'' s a      -> s -> (a -> m r) -> m ()\n-- 'forMOf_' :: 'Monad' m => 'Iso'' s a       -> s -> (a -> m r) -> m ()\n-- 'forMOf_' :: 'Monad' m => 'Traversal'' s a -> s -> (a -> m r) -> m ()\n-- 'forMOf_' :: 'Monad' m => 'Prism'' s a     -> s -> (a -> m r) -> m ()\n-- @\nforMOf_ :: Monad m => Getting (Sequenced r m) s a -> s -> (a -> m r) -> m ()\nforMOf_ = flip . mapMOf_\n{-# INLINE forMOf_ #-}\n\n-- | Evaluate each monadic action referenced by a 'Fold' on the structure from left to right, and ignore the results.\n--\n-- >>> sequenceOf_ both (putStrLn \"hello\",putStrLn \"world\")\n-- hello\n-- world\n--\n-- @\n-- 'Data.Foldable.sequence_' \u2261 'sequenceOf_' 'folded'\n-- @\n--\n-- @\n-- 'sequenceOf_' :: 'Monad' m => 'Getter' s (m a)     -> s -> m ()\n-- 'sequenceOf_' :: 'Monad' m => 'Fold' s (m a)       -> s -> m ()\n-- 'sequenceOf_' :: 'Monad' m => 'Lens'' s (m a)      -> s -> m ()\n-- 'sequenceOf_' :: 'Monad' m => 'Iso'' s (m a)       -> s -> m ()\n-- 'sequenceOf_' :: 'Monad' m => 'Traversal'' s (m a) -> s -> m ()\n-- 'sequenceOf_' :: 'Monad' m => 'Prism'' s (m a)     -> s -> m ()\n-- @\nsequenceOf_ :: Monad m => Getting (Sequenced a m) s (m a) -> s -> m ()\nsequenceOf_ l = liftM skip . getSequenced #. foldMapOf l Sequenced\n{-# INLINE sequenceOf_ #-}\n\n-- | The sum of a collection of actions, generalizing 'concatOf'.\n--\n-- >>> asumOf both (\"hello\",\"world\")\n-- \"helloworld\"\n--\n-- >>> asumOf each (Nothing, Just \"hello\", Nothing)\n-- Just \"hello\"\n--\n-- @\n-- 'asum' \u2261 'asumOf' 'folded'\n-- @\n--\n-- @\n-- 'asumOf' :: 'Alternative' f => 'Getter' s (f a)     -> s -> f a\n-- 'asumOf' :: 'Alternative' f => 'Fold' s (f a)       -> s -> f a\n-- 'asumOf' :: 'Alternative' f => 'Lens'' s (f a)      -> s -> f a\n-- 'asumOf' :: 'Alternative' f => 'Iso'' s (f a)       -> s -> f a\n-- 'asumOf' :: 'Alternative' f => 'Traversal'' s (f a) -> s -> f a\n-- 'asumOf' :: 'Alternative' f => 'Prism'' s (f a)     -> s -> f a\n-- @\nasumOf :: Alternative f => Getting (Endo (f a)) s (f a) -> s -> f a\nasumOf l = foldrOf l (<|>) empty\n{-# INLINE asumOf #-}\n\n-- | The sum of a collection of actions, generalizing 'concatOf'.\n--\n-- >>> msumOf both (\"hello\",\"world\")\n-- \"helloworld\"\n--\n-- >>> msumOf each (Nothing, Just \"hello\", Nothing)\n-- Just \"hello\"\n--\n-- @\n-- 'msum' \u2261 'msumOf' 'folded'\n-- @\n--\n-- @\n-- 'msumOf' :: 'MonadPlus' m => 'Getter' s (m a)     -> s -> m a\n-- 'msumOf' :: 'MonadPlus' m => 'Fold' s (m a)       -> s -> m a\n-- 'msumOf' :: 'MonadPlus' m => 'Lens'' s (m a)      -> s -> m a\n-- 'msumOf' :: 'MonadPlus' m => 'Iso'' s (m a)       -> s -> m a\n-- 'msumOf' :: 'MonadPlus' m => 'Traversal'' s (m a) -> s -> m a\n-- 'msumOf' :: 'MonadPlus' m => 'Prism'' s (m a)     -> s -> m a\n-- @\nmsumOf :: MonadPlus m => Getting (Endo (m a)) s (m a) -> s -> m a\nmsumOf l = foldrOf l mplus mzero\n{-# INLINE msumOf #-}\n\n-- | Does the element occur anywhere within a given 'Fold' of the structure?\n--\n-- >>> elemOf both \"hello\" (\"hello\",\"world\")\n-- True\n--\n-- @\n-- 'elem' \u2261 'elemOf' 'folded'\n-- @\n--\n-- @\n-- 'elemOf' :: 'Eq' a => 'Getter' s a     -> a -> s -> 'Bool'\n-- 'elemOf' :: 'Eq' a => 'Fold' s a       -> a -> s -> 'Bool'\n-- 'elemOf' :: 'Eq' a => 'Lens'' s a      -> a -> s -> 'Bool'\n-- 'elemOf' :: 'Eq' a => 'Iso'' s a       -> a -> s -> 'Bool'\n-- 'elemOf' :: 'Eq' a => 'Traversal'' s a -> a -> s -> 'Bool'\n-- 'elemOf' :: 'Eq' a => 'Prism'' s a     -> a -> s -> 'Bool'\n-- @\nelemOf :: Eq a => Getting Any s a -> a -> s -> Bool\nelemOf l = anyOf l . (==)\n{-# INLINE elemOf #-}\n\n-- | Does the element not occur anywhere within a given 'Fold' of the structure?\n--\n-- >>> notElemOf each 'd' ('a','b','c')\n-- True\n--\n-- >>> notElemOf each 'a' ('a','b','c')\n-- False\n--\n-- @\n-- 'notElem' \u2261 'notElemOf' 'folded'\n-- @\n--\n-- @\n-- 'notElemOf' :: 'Eq' a => 'Getter' s a     -> a -> s -> 'Bool'\n-- 'notElemOf' :: 'Eq' a => 'Fold' s a       -> a -> s -> 'Bool'\n-- 'notElemOf' :: 'Eq' a => 'Iso'' s a       -> a -> s -> 'Bool'\n-- 'notElemOf' :: 'Eq' a => 'Lens'' s a      -> a -> s -> 'Bool'\n-- 'notElemOf' :: 'Eq' a => 'Traversal'' s a -> a -> s -> 'Bool'\n-- 'notElemOf' :: 'Eq' a => 'Prism'' s a     -> a -> s -> 'Bool'\n-- @\nnotElemOf :: Eq a => Getting All s a -> a -> s -> Bool\nnotElemOf l = allOf l . (/=)\n{-# INLINE notElemOf #-}\n\n-- | Map a function over all the targets of a 'Fold' of a container and concatenate the resulting lists.\n--\n-- >>> concatMapOf both (\\x -> [x, x + 1]) (1,3)\n-- [1,2,3,4]\n--\n-- @\n-- 'concatMap' \u2261 'concatMapOf' 'folded'\n-- @\n--\n-- @\n-- 'concatMapOf' :: 'Getter' s a     -> (a -> [r]) -> s -> [r]\n-- 'concatMapOf' :: 'Fold' s a       -> (a -> [r]) -> s -> [r]\n-- 'concatMapOf' :: 'Lens'' s a      -> (a -> [r]) -> s -> [r]\n-- 'concatMapOf' :: 'Iso'' s a       -> (a -> [r]) -> s -> [r]\n-- 'concatMapOf' :: 'Traversal'' s a -> (a -> [r]) -> s -> [r]\n-- @\nconcatMapOf :: Getting [r] s a -> (a -> [r]) -> s -> [r]\nconcatMapOf = coerce\n{-# INLINE concatMapOf #-}\n\n-- | Concatenate all of the lists targeted by a 'Fold' into a longer list.\n--\n-- >>> concatOf both (\"pan\",\"ama\")\n-- \"panama\"\n--\n-- @\n-- 'concat' \u2261 'concatOf' 'folded'\n-- 'concatOf' \u2261 'view'\n-- @\n--\n-- @\n-- 'concatOf' :: 'Getter' s [r]     -> s -> [r]\n-- 'concatOf' :: 'Fold' s [r]       -> s -> [r]\n-- 'concatOf' :: 'Iso'' s [r]       -> s -> [r]\n-- 'concatOf' :: 'Lens'' s [r]      -> s -> [r]\n-- 'concatOf' :: 'Traversal'' s [r] -> s -> [r]\n-- @\nconcatOf :: Getting [r] s [r] -> s -> [r]\nconcatOf l = getConst #. l Const\n{-# INLINE concatOf #-}\n\n\n-- | Calculate the number of targets there are for a 'Fold' in a given container.\n--\n-- /Note:/ This can be rather inefficient for large containers and just like 'length',\n-- this will not terminate for infinite folds.\n--\n-- @\n-- 'length' \u2261 'lengthOf' 'folded'\n-- @\n--\n-- >>> lengthOf _1 (\"hello\",())\n-- 1\n--\n-- >>> lengthOf traverse [1..10]\n-- 10\n--\n-- >>> lengthOf (traverse.traverse) [[1,2],[3,4],[5,6]]\n-- 6\n--\n-- @\n-- 'lengthOf' ('folded' '.' 'folded') :: ('Foldable' f, 'Foldable' g) => f (g a) -> 'Int'\n-- @\n--\n-- @\n-- 'lengthOf' :: 'Getter' s a     -> s -> 'Int'\n-- 'lengthOf' :: 'Fold' s a       -> s -> 'Int'\n-- 'lengthOf' :: 'Lens'' s a      -> s -> 'Int'\n-- 'lengthOf' :: 'Iso'' s a       -> s -> 'Int'\n-- 'lengthOf' :: 'Traversal'' s a -> s -> 'Int'\n-- @\nlengthOf :: Getting (Endo (Endo Int)) s a -> s -> Int\nlengthOf l = foldlOf' l (\\a _ -> a + 1) 0\n{-# INLINE lengthOf #-}\n\n-- | Perform a safe 'head' of a 'Fold' or 'Traversal' or retrieve 'Just' the result\n-- from a 'Getter' or 'Lens'.\n--\n-- When using a 'Traversal' as a partial 'Lens', or a 'Fold' as a partial 'Getter' this can be a convenient\n-- way to extract the optional value.\n--\n-- Note: if you get stack overflows due to this, you may want to use 'firstOf' instead, which can deal\n-- more gracefully with heavily left-biased trees. This is because '^?' works by using the\n-- 'Data.Monoid.First' monoid, which can occasionally cause space leaks.\n--\n-- >>> Left 4 ^?_Left\n-- Just 4\n--\n-- >>> Right 4 ^?_Left\n-- Nothing\n--\n-- >>> \"world\" ^? ix 3\n-- Just 'l'\n--\n-- >>> \"world\" ^? ix 20\n-- Nothing\n--\n-- This operator works as an infix version of 'preview'.\n--\n-- @\n-- ('^?') \u2261 'flip' 'preview'\n-- @\n--\n-- It may be helpful to think of '^?' as having one of the following\n-- more specialized types:\n--\n-- @\n-- ('^?') :: s -> 'Getter' s a     -> 'Maybe' a\n-- ('^?') :: s -> 'Fold' s a       -> 'Maybe' a\n-- ('^?') :: s -> 'Lens'' s a      -> 'Maybe' a\n-- ('^?') :: s -> 'Iso'' s a       -> 'Maybe' a\n-- ('^?') :: s -> 'Traversal'' s a -> 'Maybe' a\n-- @\n(^?) :: s -> Getting (First a) s a -> Maybe a\ns ^? l = getFirst (foldMapOf l (First #. Just) s)\n{-# INLINE (^?) #-}\n\n-- | Perform an *UNSAFE* 'head' of a 'Fold' or 'Traversal' assuming that it is there.\n--\n-- >>> Left 4 ^?! _Left\n-- 4\n--\n-- >>> \"world\" ^?! ix 3\n-- 'l'\n--\n-- @\n-- ('^?!') :: s -> 'Getter' s a     -> a\n-- ('^?!') :: s -> 'Fold' s a       -> a\n-- ('^?!') :: s -> 'Lens'' s a      -> a\n-- ('^?!') :: s -> 'Iso'' s a       -> a\n-- ('^?!') :: s -> 'Traversal'' s a -> a\n-- @\n(^?!) :: HasCallStack => s -> Getting (Endo a) s a -> a\ns ^?! l = foldrOf l const (error \"(^?!): empty Fold\") s\n{-# INLINE (^?!) #-}\n\n-- | Retrieve the 'First' entry of a 'Fold' or 'Traversal' or retrieve 'Just' the result\n-- from a 'Getter' or 'Lens'.\n--\n-- The answer is computed in a manner that leaks space less than @'preview'@ or @^?'@\n-- and gives you back access to the outermost 'Just' constructor more quickly, but does so\n-- in a way that builds an intermediate structure, and thus may have worse\n-- constant factors. This also means that it can not be used in any 'Control.Monad.Reader.MonadReader',\n-- but must instead have 's' passed as its last argument, unlike 'preview'.\n--\n-- Note: this could been named `headOf`.\n--\n-- >>> firstOf traverse [1..10]\n-- Just 1\n--\n-- >>> firstOf both (1,2)\n-- Just 1\n--\n-- >>> firstOf ignored ()\n-- Nothing\n--\n-- @\n-- 'firstOf' :: 'Getter' s a     -> s -> 'Maybe' a\n-- 'firstOf' :: 'Fold' s a       -> s -> 'Maybe' a\n-- 'firstOf' :: 'Lens'' s a      -> s -> 'Maybe' a\n-- 'firstOf' :: 'Iso'' s a       -> s -> 'Maybe' a\n-- 'firstOf' :: 'Traversal'' s a -> s -> 'Maybe' a\n-- @\nfirstOf :: Getting (Leftmost a) s a -> s -> Maybe a\nfirstOf l = getLeftmost . foldMapOf l LLeaf\n{-# INLINE firstOf #-}\n\n-- | Retrieve the 'Data.Semigroup.First' entry of a 'Fold1' or 'Traversal1' or the result from a 'Getter' or 'Lens'.\n--\n-- >>> first1Of traverse1 (1 :| [2..10])\n-- 1\n--\n-- >>> first1Of both1 (1,2)\n-- 1\n--\n-- /Note:/ this is different from '^.'.\n--\n-- >>> first1Of traverse1 ([1,2] :| [[3,4],[5,6]])\n-- [1,2]\n--\n-- >>> ([1,2] :| [[3,4],[5,6]]) ^. traverse1\n-- [1,2,3,4,5,6]\n--\n-- @\n-- 'first1Of' :: 'Getter' s a      -> s -> a\n-- 'first1Of' :: 'Fold1' s a       -> s -> a\n-- 'first1Of' :: 'Lens'' s a       -> s -> a\n-- 'first1Of' :: 'Iso'' s a        -> s -> a\n-- 'first1Of' :: 'Traversal1'' s a -> s -> a\n-- @\nfirst1Of :: Getting (Semi.First a) s a -> s -> a\nfirst1Of l = Semi.getFirst . foldMapOf l Semi.First\n\n-- | Retrieve the 'Last' entry of a 'Fold' or 'Traversal' or retrieve 'Just' the result\n-- from a 'Getter' or 'Lens'.\n--\n-- The answer is computed in a manner that leaks space less than @'ala' 'Last' '.' 'foldMapOf'@\n-- and gives you back access to the outermost 'Just' constructor more quickly, but may have worse\n-- constant factors.\n--\n-- >>> lastOf traverse [1..10]\n-- Just 10\n--\n-- >>> lastOf both (1,2)\n-- Just 2\n--\n-- >>> lastOf ignored ()\n-- Nothing\n--\n-- @\n-- 'lastOf' :: 'Getter' s a     -> s -> 'Maybe' a\n-- 'lastOf' :: 'Fold' s a       -> s -> 'Maybe' a\n-- 'lastOf' :: 'Lens'' s a      -> s -> 'Maybe' a\n-- 'lastOf' :: 'Iso'' s a       -> s -> 'Maybe' a\n-- 'lastOf' :: 'Traversal'' s a -> s -> 'Maybe' a\n-- @\nlastOf :: Getting (Rightmost a) s a -> s -> Maybe a\nlastOf l = getRightmost . foldMapOf l RLeaf\n{-# INLINE lastOf #-}\n\n-- | Retrieve the 'Data.Semigroup.Last' entry of a 'Fold1' or 'Traversal1' or retrieve the result\n-- from a 'Getter' or 'Lens'.o\n--\n-- >>> last1Of traverse1 (1 :| [2..10])\n-- 10\n--\n-- >>> last1Of both1 (1,2)\n-- 2\n--\n-- @\n-- 'last1Of' :: 'Getter' s a      -> s -> 'Maybe' a\n-- 'last1Of' :: 'Fold1' s a       -> s -> 'Maybe' a\n-- 'last1Of' :: 'Lens'' s a       -> s -> 'Maybe' a\n-- 'last1Of' :: 'Iso'' s a        -> s -> 'Maybe' a\n-- 'last1Of' :: 'Traversal1'' s a -> s -> 'Maybe' a\n-- @\nlast1Of :: Getting (Semi.Last a) s a -> s -> a\nlast1Of l = Semi.getLast . foldMapOf l Semi.Last\n\n-- | Returns 'True' if this 'Fold' or 'Traversal' has no targets in the given container.\n--\n-- Note: 'nullOf' on a valid 'Iso', 'Lens' or 'Getter' should always return 'False'.\n--\n-- @\n-- 'null' \u2261 'nullOf' 'folded'\n-- @\n--\n-- This may be rather inefficient compared to the 'null' check of many containers.\n--\n-- >>> nullOf _1 (1,2)\n-- False\n--\n-- >>> nullOf ignored ()\n-- True\n--\n-- >>> nullOf traverse []\n-- True\n--\n-- >>> nullOf (element 20) [1..10]\n-- True\n--\n-- @\n-- 'nullOf' ('folded' '.' '_1' '.' 'folded') :: ('Foldable' f, 'Foldable' g) => f (g a, b) -> 'Bool'\n-- @\n--\n-- @\n-- 'nullOf' :: 'Getter' s a     -> s -> 'Bool'\n-- 'nullOf' :: 'Fold' s a       -> s -> 'Bool'\n-- 'nullOf' :: 'Iso'' s a       -> s -> 'Bool'\n-- 'nullOf' :: 'Lens'' s a      -> s -> 'Bool'\n-- 'nullOf' :: 'Traversal'' s a -> s -> 'Bool'\n-- @\nnullOf :: Getting All s a -> s -> Bool\nnullOf = hasn't\n{-# INLINE nullOf #-}\n\n-- | Returns 'True' if this 'Fold' or 'Traversal' has any targets in the given container.\n--\n-- A more \\\"conversational\\\" alias for this combinator is 'has'.\n--\n-- Note: 'notNullOf' on a valid 'Iso', 'Lens' or 'Getter' should always return 'True'.\n--\n-- @\n-- 'not' '.' 'null' \u2261 'notNullOf' 'folded'\n-- @\n--\n-- This may be rather inefficient compared to the @'not' '.' 'null'@ check of many containers.\n--\n-- >>> notNullOf _1 (1,2)\n-- True\n--\n-- >>> notNullOf traverse [1..10]\n-- True\n--\n-- >>> notNullOf folded []\n-- False\n--\n-- >>> notNullOf (element 20) [1..10]\n-- False\n--\n-- @\n-- 'notNullOf' ('folded' '.' '_1' '.' 'folded') :: ('Foldable' f, 'Foldable' g) => f (g a, b) -> 'Bool'\n-- @\n--\n-- @\n-- 'notNullOf' :: 'Getter' s a     -> s -> 'Bool'\n-- 'notNullOf' :: 'Fold' s a       -> s -> 'Bool'\n-- 'notNullOf' :: 'Iso'' s a       -> s -> 'Bool'\n-- 'notNullOf' :: 'Lens'' s a      -> s -> 'Bool'\n-- 'notNullOf' :: 'Traversal'' s a -> s -> 'Bool'\n-- @\nnotNullOf :: Getting Any s a -> s -> Bool\nnotNullOf = has\n{-# INLINE notNullOf #-}\n\n-- | Obtain the maximum element (if any) targeted by a 'Fold' or 'Traversal' safely.\n--\n-- Note: 'maximumOf' on a valid 'Iso', 'Lens' or 'Getter' will always return 'Just' a value.\n--\n-- >>> maximumOf traverse [1..10]\n-- Just 10\n--\n-- >>> maximumOf traverse []\n-- Nothing\n--\n-- >>> maximumOf (folded.filtered even) [1,4,3,6,7,9,2]\n-- Just 6\n--\n-- @\n-- 'maximum' \u2261 'fromMaybe' ('error' \\\"empty\\\") '.' 'maximumOf' 'folded'\n-- @\n--\n-- In the interest of efficiency, This operation has semantics more strict than strictly necessary.\n-- @'rmap' 'getMax' ('foldMapOf' l 'Max')@ has lazier semantics but could leak memory.\n--\n-- @\n-- 'maximumOf' :: 'Ord' a => 'Getter' s a     -> s -> 'Maybe' a\n-- 'maximumOf' :: 'Ord' a => 'Fold' s a       -> s -> 'Maybe' a\n-- 'maximumOf' :: 'Ord' a => 'Iso'' s a       -> s -> 'Maybe' a\n-- 'maximumOf' :: 'Ord' a => 'Lens'' s a      -> s -> 'Maybe' a\n-- 'maximumOf' :: 'Ord' a => 'Traversal'' s a -> s -> 'Maybe' a\n-- @\nmaximumOf :: Ord a => Getting (Endo (Endo (Maybe a))) s a -> s -> Maybe a\nmaximumOf l = foldlOf' l mf Nothing where\n  mf Nothing y = Just $! y\n  mf (Just x) y = Just $! max x y\n{-# INLINE maximumOf #-}\n\n-- | Obtain the maximum element targeted by a 'Fold1' or 'Traversal1'.\n--\n-- >>> maximum1Of traverse1 (1 :| [2..10])\n-- 10\n--\n-- @\n-- 'maximum1Of' :: 'Ord' a => 'Getter' s a      -> s -> a\n-- 'maximum1Of' :: 'Ord' a => 'Fold1' s a       -> s -> a\n-- 'maximum1Of' :: 'Ord' a => 'Iso'' s a        -> s -> a\n-- 'maximum1Of' :: 'Ord' a => 'Lens'' s a       -> s -> a\n-- 'maximum1Of' :: 'Ord' a => 'Traversal1'' s a -> s -> a\n-- @\nmaximum1Of :: Ord a => Getting (Semi.Max a) s a -> s -> a\nmaximum1Of l = Semi.getMax . foldMapOf l Semi.Max\n{-# INLINE maximum1Of #-}\n\n-- | Obtain the minimum element (if any) targeted by a 'Fold' or 'Traversal' safely.\n--\n-- Note: 'minimumOf' on a valid 'Iso', 'Lens' or 'Getter' will always return 'Just' a value.\n--\n-- >>> minimumOf traverse [1..10]\n-- Just 1\n--\n-- >>> minimumOf traverse []\n-- Nothing\n--\n-- >>> minimumOf (folded.filtered even) [1,4,3,6,7,9,2]\n-- Just 2\n--\n-- @\n-- 'minimum' \u2261 'Data.Maybe.fromMaybe' ('error' \\\"empty\\\") '.' 'minimumOf' 'folded'\n-- @\n--\n-- In the interest of efficiency, This operation has semantics more strict than strictly necessary.\n-- @'rmap' 'getMin' ('foldMapOf' l 'Min')@ has lazier semantics but could leak memory.\n--\n--\n-- @\n-- 'minimumOf' :: 'Ord' a => 'Getter' s a     -> s -> 'Maybe' a\n-- 'minimumOf' :: 'Ord' a => 'Fold' s a       -> s -> 'Maybe' a\n-- 'minimumOf' :: 'Ord' a => 'Iso'' s a       -> s -> 'Maybe' a\n-- 'minimumOf' :: 'Ord' a => 'Lens'' s a      -> s -> 'Maybe' a\n-- 'minimumOf' :: 'Ord' a => 'Traversal'' s a -> s -> 'Maybe' a\n-- @\nminimumOf :: Ord a => Getting (Endo (Endo (Maybe a))) s a -> s -> Maybe a\nminimumOf l = foldlOf' l mf Nothing where\n  mf Nothing y = Just $! y\n  mf (Just x) y = Just $! min x y\n{-# INLINE minimumOf #-}\n\n-- | Obtain the minimum element targeted by a 'Fold1' or 'Traversal1'.\n--\n-- >>> minimum1Of traverse1 (1 :| [2..10])\n-- 1\n--\n-- @\n-- 'minimum1Of' :: 'Ord' a => 'Getter' s a      -> s -> a\n-- 'minimum1Of' :: 'Ord' a => 'Fold1' s a       -> s -> a\n-- 'minimum1Of' :: 'Ord' a => 'Iso'' s a        -> s -> a\n-- 'minimum1Of' :: 'Ord' a => 'Lens'' s a       -> s -> a\n-- 'minimum1Of' :: 'Ord' a => 'Traversal1'' s a -> s -> a\n-- @\nminimum1Of :: Ord a => Getting (Semi.Min a) s a -> s -> a\nminimum1Of l = Semi.getMin . foldMapOf l Semi.Min\n{-# INLINE minimum1Of #-}\n\n-- | Obtain the maximum element (if any) targeted by a 'Fold', 'Traversal', 'Lens', 'Iso',\n-- or 'Getter' according to a user supplied 'Ordering'.\n--\n-- >>> maximumByOf traverse (compare `on` length) [\"mustard\",\"relish\",\"ham\"]\n-- Just \"mustard\"\n--\n-- In the interest of efficiency, This operation has semantics more strict than strictly necessary.\n--\n-- @\n-- 'Data.Foldable.maximumBy' cmp \u2261 'Data.Maybe.fromMaybe' ('error' \\\"empty\\\") '.' 'maximumByOf' 'folded' cmp\n-- @\n--\n-- @\n-- 'maximumByOf' :: 'Getter' s a     -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- 'maximumByOf' :: 'Fold' s a       -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- 'maximumByOf' :: 'Iso'' s a       -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- 'maximumByOf' :: 'Lens'' s a      -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- 'maximumByOf' :: 'Traversal'' s a -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- @\nmaximumByOf :: Getting (Endo (Endo (Maybe a))) s a -> (a -> a -> Ordering) -> s -> Maybe a\nmaximumByOf l cmp = foldlOf' l mf Nothing where\n  mf Nothing y = Just $! y\n  mf (Just x) y = Just $! if cmp x y == GT then x else y\n{-# INLINE maximumByOf #-}\n\n-- | Obtain the minimum element (if any) targeted by a 'Fold', 'Traversal', 'Lens', 'Iso'\n-- or 'Getter' according to a user supplied 'Ordering'.\n--\n-- In the interest of efficiency, This operation has semantics more strict than strictly necessary.\n--\n-- >>> minimumByOf traverse (compare `on` length) [\"mustard\",\"relish\",\"ham\"]\n-- Just \"ham\"\n--\n-- @\n-- 'minimumBy' cmp \u2261 'Data.Maybe.fromMaybe' ('error' \\\"empty\\\") '.' 'minimumByOf' 'folded' cmp\n-- @\n--\n-- @\n-- 'minimumByOf' :: 'Getter' s a     -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- 'minimumByOf' :: 'Fold' s a       -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- 'minimumByOf' :: 'Iso'' s a       -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- 'minimumByOf' :: 'Lens'' s a      -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- 'minimumByOf' :: 'Traversal'' s a -> (a -> a -> 'Ordering') -> s -> 'Maybe' a\n-- @\nminimumByOf :: Getting (Endo (Endo (Maybe a))) s a -> (a -> a -> Ordering) -> s -> Maybe a\nminimumByOf l cmp = foldlOf' l mf Nothing where\n  mf Nothing y = Just $! y\n  mf (Just x) y = Just $! if cmp x y == GT then y else x\n{-# INLINE minimumByOf #-}\n\n-- | The 'findOf' function takes a 'Lens' (or 'Getter', 'Iso', 'Fold', or 'Traversal'),\n-- a predicate and a structure and returns the leftmost element of the structure\n-- matching the predicate, or 'Nothing' if there is no such element.\n--\n-- >>> findOf each even (1,3,4,6)\n-- Just 4\n--\n-- >>> findOf folded even [1,3,5,7]\n-- Nothing\n--\n-- @\n-- 'findOf' :: 'Getter' s a     -> (a -> 'Bool') -> s -> 'Maybe' a\n-- 'findOf' :: 'Fold' s a       -> (a -> 'Bool') -> s -> 'Maybe' a\n-- 'findOf' :: 'Iso'' s a       -> (a -> 'Bool') -> s -> 'Maybe' a\n-- 'findOf' :: 'Lens'' s a      -> (a -> 'Bool') -> s -> 'Maybe' a\n-- 'findOf' :: 'Traversal'' s a -> (a -> 'Bool') -> s -> 'Maybe' a\n-- @\n--\n-- @\n-- 'Data.Foldable.find' \u2261 'findOf' 'folded'\n-- 'ifindOf' l \u2261 'findOf' l '.' 'Indexed'\n-- @\n--\n-- A simpler version that didn't permit indexing, would be:\n--\n-- @\n-- 'findOf' :: 'Getting' ('Endo' ('Maybe' a)) s a -> (a -> 'Bool') -> s -> 'Maybe' a\n-- 'findOf' l p = 'foldrOf' l (\\a y -> if p a then 'Just' a else y) 'Nothing'\n-- @\nfindOf :: Getting (Endo (Maybe a)) s a -> (a -> Bool) -> s -> Maybe a\nfindOf l f = foldrOf l (\\a y -> if f a then Just a else y) Nothing\n{-# INLINE findOf #-}\n\n-- | The 'findMOf' function takes a 'Lens' (or 'Getter', 'Iso', 'Fold', or 'Traversal'),\n-- a monadic predicate and a structure and returns in the monad the leftmost element of the structure\n-- matching the predicate, or 'Nothing' if there is no such element.\n--\n-- >>>  findMOf each ( \\x -> print (\"Checking \" ++ show x) >> return (even x)) (1,3,4,6)\n-- \"Checking 1\"\n-- \"Checking 3\"\n-- \"Checking 4\"\n-- Just 4\n--\n-- >>>  findMOf each ( \\x -> print (\"Checking \" ++ show x) >> return (even x)) (1,3,5,7)\n-- \"Checking 1\"\n-- \"Checking 3\"\n-- \"Checking 5\"\n-- \"Checking 7\"\n-- Nothing\n--\n-- @\n-- 'findMOf' :: ('Monad' m, 'Getter' s a)     -> (a -> m 'Bool') -> s -> m ('Maybe' a)\n-- 'findMOf' :: ('Monad' m, 'Fold' s a)       -> (a -> m 'Bool') -> s -> m ('Maybe' a)\n-- 'findMOf' :: ('Monad' m, 'Iso'' s a)       -> (a -> m 'Bool') -> s -> m ('Maybe' a)\n-- 'findMOf' :: ('Monad' m, 'Lens'' s a)      -> (a -> m 'Bool') -> s -> m ('Maybe' a)\n-- 'findMOf' :: ('Monad' m, 'Traversal'' s a) -> (a -> m 'Bool') -> s -> m ('Maybe' a)\n-- @\n--\n-- @\n-- 'findMOf' 'folded' :: (Monad m, Foldable f) => (a -> m Bool) -> f a -> m (Maybe a)\n-- 'ifindMOf' l \u2261 'findMOf' l '.' 'Indexed'\n-- @\n--\n-- A simpler version that didn't permit indexing, would be:\n--\n-- @\n-- 'findMOf' :: Monad m => 'Getting' ('Endo' (m ('Maybe' a))) s a -> (a -> m 'Bool') -> s -> m ('Maybe' a)\n-- 'findMOf' l p = 'foldrOf' l (\\a y -> p a >>= \\x -> if x then return ('Just' a) else y) $ return 'Nothing'\n-- @\nfindMOf :: Monad m => Getting (Endo (m (Maybe a))) s a -> (a -> m Bool) -> s -> m (Maybe a)\nfindMOf l f = foldrOf l (\\a y -> f a >>= \\r -> if r then return (Just a) else y) $ return Nothing\n{-# INLINE findMOf #-}\n\n-- | The 'lookupOf' function takes a 'Fold' (or 'Getter', 'Traversal',\n-- 'Lens', 'Iso', etc.), a key, and a structure containing key/value pairs.\n-- It returns the first value corresponding to the given key. This function\n-- generalizes 'lookup' to work on an arbitrary 'Fold' instead of lists.\n--\n-- >>> lookupOf folded 4 [(2, 'a'), (4, 'b'), (4, 'c')]\n-- Just 'b'\n--\n-- >>> lookupOf each 2 [(2, 'a'), (4, 'b'), (4, 'c')]\n-- Just 'a'\n--\n-- @\n-- 'lookupOf' :: 'Eq' k => 'Fold' s (k,v) -> k -> s -> 'Maybe' v\n-- @\nlookupOf :: Eq k => Getting (Endo (Maybe v)) s (k,v) -> k -> s -> Maybe v\nlookupOf l k = foldrOf l (\\(k',v) next -> if k == k' then Just v else next) Nothing\n{-# INLINE lookupOf #-}\n\n-- | A variant of 'foldrOf' that has no base case and thus may only be applied\n-- to lenses and structures such that the 'Lens' views at least one element of\n-- the structure.\n--\n-- >>> foldr1Of each (+) (1,2,3,4)\n-- 10\n--\n-- @\n-- 'foldr1Of' l f \u2261 'Prelude.foldr1' f '.' 'toListOf' l\n-- 'Data.Foldable.foldr1' \u2261 'foldr1Of' 'folded'\n-- @\n--\n-- @\n-- 'foldr1Of' :: 'Getter' s a     -> (a -> a -> a) -> s -> a\n-- 'foldr1Of' :: 'Fold' s a       -> (a -> a -> a) -> s -> a\n-- 'foldr1Of' :: 'Iso'' s a       -> (a -> a -> a) -> s -> a\n-- 'foldr1Of' :: 'Lens'' s a      -> (a -> a -> a) -> s -> a\n-- 'foldr1Of' :: 'Traversal'' s a -> (a -> a -> a) -> s -> a\n-- @\nfoldr1Of :: HasCallStack => Getting (Endo (Maybe a)) s a -> (a -> a -> a) -> s -> a\nfoldr1Of l f xs = fromMaybe (error \"foldr1Of: empty structure\")\n                            (foldrOf l mf Nothing xs) where\n  mf x my = Just $ case my of\n    Nothing -> x\n    Just y -> f x y\n{-# INLINE foldr1Of #-}\n\n-- | A variant of 'foldlOf' that has no base case and thus may only be applied to lenses and structures such\n-- that the 'Lens' views at least one element of the structure.\n--\n-- >>> foldl1Of each (+) (1,2,3,4)\n-- 10\n--\n-- @\n-- 'foldl1Of' l f \u2261 'Prelude.foldl1' f '.' 'toListOf' l\n-- 'Data.Foldable.foldl1' \u2261 'foldl1Of' 'folded'\n-- @\n--\n-- @\n-- 'foldl1Of' :: 'Getter' s a     -> (a -> a -> a) -> s -> a\n-- 'foldl1Of' :: 'Fold' s a       -> (a -> a -> a) -> s -> a\n-- 'foldl1Of' :: 'Iso'' s a       -> (a -> a -> a) -> s -> a\n-- 'foldl1Of' :: 'Lens'' s a      -> (a -> a -> a) -> s -> a\n-- 'foldl1Of' :: 'Traversal'' s a -> (a -> a -> a) -> s -> a\n-- @\nfoldl1Of :: HasCallStack => Getting (Dual (Endo (Maybe a))) s a -> (a -> a -> a) -> s -> a\nfoldl1Of l f xs = fromMaybe (error \"foldl1Of: empty structure\") (foldlOf l mf Nothing xs) where\n  mf mx y = Just $ case mx of\n    Nothing -> y\n    Just x  -> f x y\n{-# INLINE foldl1Of #-}\n\n-- | Strictly fold right over the elements of a structure.\n--\n-- @\n-- 'Data.Foldable.foldr'' \u2261 'foldrOf'' 'folded'\n-- @\n--\n-- @\n-- 'foldrOf'' :: 'Getter' s a     -> (a -> r -> r) -> r -> s -> r\n-- 'foldrOf'' :: 'Fold' s a       -> (a -> r -> r) -> r -> s -> r\n-- 'foldrOf'' :: 'Iso'' s a       -> (a -> r -> r) -> r -> s -> r\n-- 'foldrOf'' :: 'Lens'' s a      -> (a -> r -> r) -> r -> s -> r\n-- 'foldrOf'' :: 'Traversal'' s a -> (a -> r -> r) -> r -> s -> r\n-- @\nfoldrOf' :: Getting (Dual (Endo (Endo r))) s a -> (a -> r -> r) -> r -> s -> r\nfoldrOf' l f z0 xs = foldlOf l f' (Endo id) xs `appEndo` z0\n  where f' (Endo k) x = Endo $ \\ z -> k $! f x z\n{-# INLINE foldrOf' #-}\n\n-- | Fold over the elements of a structure, associating to the left, but strictly.\n--\n-- @\n-- 'Data.Foldable.foldl'' \u2261 'foldlOf'' 'folded'\n-- @\n--\n-- @\n-- 'foldlOf'' :: 'Getter' s a     -> (r -> a -> r) -> r -> s -> r\n-- 'foldlOf'' :: 'Fold' s a       -> (r -> a -> r) -> r -> s -> r\n-- 'foldlOf'' :: 'Iso'' s a       -> (r -> a -> r) -> r -> s -> r\n-- 'foldlOf'' :: 'Lens'' s a      -> (r -> a -> r) -> r -> s -> r\n-- 'foldlOf'' :: 'Traversal'' s a -> (r -> a -> r) -> r -> s -> r\n-- @\nfoldlOf' :: Getting (Endo (Endo r)) s a -> (r -> a -> r) -> r -> s -> r\nfoldlOf' l f z0 xs = foldrOf l f' (Endo id) xs `appEndo` z0\n  where f' x (Endo k) = Endo $ \\z -> k $! f z x\n{-# INLINE foldlOf' #-}\n\n-- | A variant of 'foldrOf'' that has no base case and thus may only be applied\n-- to folds and structures such that the fold views at least one element of the\n-- structure.\n--\n-- @\n-- 'foldr1Of' l f \u2261 'Prelude.foldr1' f '.' 'toListOf' l\n-- @\n--\n-- @\n-- 'foldr1Of'' :: 'Getter' s a     -> (a -> a -> a) -> s -> a\n-- 'foldr1Of'' :: 'Fold' s a       -> (a -> a -> a) -> s -> a\n-- 'foldr1Of'' :: 'Iso'' s a       -> (a -> a -> a) -> s -> a\n-- 'foldr1Of'' :: 'Lens'' s a      -> (a -> a -> a) -> s -> a\n-- 'foldr1Of'' :: 'Traversal'' s a -> (a -> a -> a) -> s -> a\n-- @\nfoldr1Of' :: HasCallStack => Getting (Dual (Endo (Endo (Maybe a)))) s a -> (a -> a -> a) -> s -> a\nfoldr1Of' l f xs = fromMaybe (error \"foldr1Of': empty structure\") (foldrOf' l mf Nothing xs) where\n  mf x Nothing = Just $! x\n  mf x (Just y) = Just $! f x y\n{-# INLINE foldr1Of' #-}\n\n-- | A variant of 'foldlOf'' that has no base case and thus may only be applied\n-- to folds and structures such that the fold views at least one element of\n-- the structure.\n--\n-- @\n-- 'foldl1Of'' l f \u2261 'Data.List.foldl1'' f '.' 'toListOf' l\n-- @\n--\n-- @\n-- 'foldl1Of'' :: 'Getter' s a     -> (a -> a -> a) -> s -> a\n-- 'foldl1Of'' :: 'Fold' s a       -> (a -> a -> a) -> s -> a\n-- 'foldl1Of'' :: 'Iso'' s a       -> (a -> a -> a) -> s -> a\n-- 'foldl1Of'' :: 'Lens'' s a      -> (a -> a -> a) -> s -> a\n-- 'foldl1Of'' :: 'Traversal'' s a -> (a -> a -> a) -> s -> a\n-- @\nfoldl1Of' :: HasCallStack => Getting (Endo (Endo (Maybe a))) s a -> (a -> a -> a) -> s -> a\nfoldl1Of' l f xs = fromMaybe (error \"foldl1Of': empty structure\") (foldlOf' l mf Nothing xs) where\n  mf Nothing y = Just $! y\n  mf (Just x) y = Just $! f x y\n{-# INLINE foldl1Of' #-}\n\n-- | Monadic fold over the elements of a structure, associating to the right,\n-- i.e. from right to left.\n--\n-- @\n-- 'Data.Foldable.foldrM' \u2261 'foldrMOf' 'folded'\n-- @\n--\n-- @\n-- 'foldrMOf' :: 'Monad' m => 'Getter' s a     -> (a -> r -> m r) -> r -> s -> m r\n-- 'foldrMOf' :: 'Monad' m => 'Fold' s a       -> (a -> r -> m r) -> r -> s -> m r\n-- 'foldrMOf' :: 'Monad' m => 'Iso'' s a       -> (a -> r -> m r) -> r -> s -> m r\n-- 'foldrMOf' :: 'Monad' m => 'Lens'' s a      -> (a -> r -> m r) -> r -> s -> m r\n-- 'foldrMOf' :: 'Monad' m => 'Traversal'' s a -> (a -> r -> m r) -> r -> s -> m r\n-- @\nfoldrMOf :: Monad m\n         => Getting (Dual (Endo (r -> m r))) s a\n         -> (a -> r -> m r) -> r -> s -> m r\nfoldrMOf l f z0 xs = foldlOf l f' return xs z0\n  where f' k x z = f x z >>= k\n{-# INLINE foldrMOf #-}\n\n-- | Monadic fold over the elements of a structure, associating to the left,\n-- i.e. from left to right.\n--\n-- @\n-- 'Data.Foldable.foldlM' \u2261 'foldlMOf' 'folded'\n-- @\n--\n-- @\n-- 'foldlMOf' :: 'Monad' m => 'Getter' s a     -> (r -> a -> m r) -> r -> s -> m r\n-- 'foldlMOf' :: 'Monad' m => 'Fold' s a       -> (r -> a -> m r) -> r -> s -> m r\n-- 'foldlMOf' :: 'Monad' m => 'Iso'' s a       -> (r -> a -> m r) -> r -> s -> m r\n-- 'foldlMOf' :: 'Monad' m => 'Lens'' s a      -> (r -> a -> m r) -> r -> s -> m r\n-- 'foldlMOf' :: 'Monad' m => 'Traversal'' s a -> (r -> a -> m r) -> r -> s -> m r\n-- @\nfoldlMOf :: Monad m\n         => Getting (Endo (r -> m r)) s a\n         -> (r -> a -> m r) -> r -> s -> m r\nfoldlMOf l f z0 xs = foldrOf l f' return xs z0\n  where f' x k z = f z x >>= k\n{-# INLINE foldlMOf #-}\n\n-- | Check to see if this 'Fold' or 'Traversal' matches 1 or more entries.\n--\n-- >>> has (element 0) []\n-- False\n--\n-- >>> has _Left (Left 12)\n-- True\n--\n-- >>> has _Right (Left 12)\n-- False\n--\n-- This will always return 'True' for a 'Lens' or 'Getter'.\n--\n-- >>> has _1 (\"hello\",\"world\")\n-- True\n--\n-- @\n-- 'has' :: 'Getter' s a     -> s -> 'Bool'\n-- 'has' :: 'Fold' s a       -> s -> 'Bool'\n-- 'has' :: 'Iso'' s a       -> s -> 'Bool'\n-- 'has' :: 'Lens'' s a      -> s -> 'Bool'\n-- 'has' :: 'Traversal'' s a -> s -> 'Bool'\n-- @\nhas :: Getting Any s a -> s -> Bool\nhas l = getAny #. foldMapOf l (\\_ -> Any True)\n{-# INLINE has #-}\n\n\n\n-- | Check to see if this 'Fold' or 'Traversal' has no matches.\n--\n-- >>> hasn't _Left (Right 12)\n-- True\n--\n-- >>> hasn't _Left (Left 12)\n-- False\nhasn't :: Getting All s a -> s -> Bool\nhasn't l = getAll #. foldMapOf l (\\_ -> All False)\n{-# INLINE hasn't #-}\n\n------------------------------------------------------------------------------\n-- Pre\n------------------------------------------------------------------------------\n\n-- | This converts a 'Fold' to a 'IndexPreservingGetter' that returns the first element, if it\n-- exists, as a 'Maybe'.\n--\n-- @\n-- 'pre' :: 'Getter' s a     -> 'IndexPreservingGetter' s ('Maybe' a)\n-- 'pre' :: 'Fold' s a       -> 'IndexPreservingGetter' s ('Maybe' a)\n-- 'pre' :: 'Traversal'' s a -> 'IndexPreservingGetter' s ('Maybe' a)\n-- 'pre' :: 'Lens'' s a      -> 'IndexPreservingGetter' s ('Maybe' a)\n-- 'pre' :: 'Iso'' s a       -> 'IndexPreservingGetter' s ('Maybe' a)\n-- 'pre' :: 'Prism'' s a     -> 'IndexPreservingGetter' s ('Maybe' a)\n-- @\npre :: Getting (First a) s a -> IndexPreservingGetter s (Maybe a)\npre l = dimap (getFirst . getConst #. l (Const #. First #. Just)) phantom\n{-# INLINE pre #-}\n\n-- | This converts an 'IndexedFold' to an 'IndexPreservingGetter' that returns the first index\n-- and element, if they exist, as a 'Maybe'.\n--\n-- @\n-- 'ipre' :: 'IndexedGetter' i s a     -> 'IndexPreservingGetter' s ('Maybe' (i, a))\n-- 'ipre' :: 'IndexedFold' i s a       -> 'IndexPreservingGetter' s ('Maybe' (i, a))\n-- 'ipre' :: 'IndexedTraversal'' i s a -> 'IndexPreservingGetter' s ('Maybe' (i, a))\n-- 'ipre' :: 'IndexedLens'' i s a      -> 'IndexPreservingGetter' s ('Maybe' (i, a))\n-- @\nipre :: IndexedGetting i (First (i, a)) s a -> IndexPreservingGetter s (Maybe (i, a))\nipre l = dimap (getFirst . getConst #. l (Indexed $ \\i a -> Const (First (Just (i, a))))) phantom\n{-# INLINE ipre #-}\n\n------------------------------------------------------------------------------\n-- Preview\n------------------------------------------------------------------------------\n\n-- | Retrieve the first value targeted by a 'Fold' or 'Traversal' (or 'Just' the result\n-- from a 'Getter' or 'Lens'). See also 'firstOf' and '^?', which are similar with\n-- some subtle differences (explained below).\n--\n-- @\n-- 'Data.Maybe.listToMaybe' '.' 'toList' \u2261 'preview' 'folded'\n-- @\n--\n-- @\n-- 'preview' = 'view' '.' 'pre'\n-- @\n--\n--\n-- Unlike '^?', this function uses a\n-- 'Control.Monad.Reader.MonadReader' to read the value to be focused in on.\n-- This allows one to pass the value as the last argument by using the\n-- 'Control.Monad.Reader.MonadReader' instance for @(->) s@\n-- However, it may also be used as part of some deeply nested transformer stack.\n--\n-- 'preview' uses a monoidal value to obtain the result.\n-- This means that it generally has good performance, but can occasionally cause space leaks\n-- or even stack overflows on some data types.\n-- There is another function, 'firstOf', which avoids these issues at the cost of\n-- a slight constant performance cost and a little less flexibility.\n--\n-- It may be helpful to think of 'preview' as having one of the following\n-- more specialized types:\n--\n-- @\n-- 'preview' :: 'Getter' s a     -> s -> 'Maybe' a\n-- 'preview' :: 'Fold' s a       -> s -> 'Maybe' a\n-- 'preview' :: 'Lens'' s a      -> s -> 'Maybe' a\n-- 'preview' :: 'Iso'' s a       -> s -> 'Maybe' a\n-- 'preview' :: 'Traversal'' s a -> s -> 'Maybe' a\n-- @\n--\n--\n-- @\n-- 'preview' :: 'MonadReader' s m => 'Getter' s a     -> m ('Maybe' a)\n-- 'preview' :: 'MonadReader' s m => 'Fold' s a       -> m ('Maybe' a)\n-- 'preview' :: 'MonadReader' s m => 'Lens'' s a      -> m ('Maybe' a)\n-- 'preview' :: 'MonadReader' s m => 'Iso'' s a       -> m ('Maybe' a)\n-- 'preview' :: 'MonadReader' s m => 'Traversal'' s a -> m ('Maybe' a)\n--\n-- @\npreview :: MonadReader s m => Getting (First a) s a -> m (Maybe a)\npreview l = asks (getFirst #. foldMapOf l (First #. Just))\n{-# INLINE preview #-}\n\n-- | Retrieve the first index and value targeted by a 'Fold' or 'Traversal' (or 'Just' the result\n-- from a 'Getter' or 'Lens'). See also ('^@?').\n--\n-- @\n-- 'ipreview' = 'view' '.' 'ipre'\n-- @\n--\n-- This is usually applied in the 'Control.Monad.Reader.Reader'\n-- 'Control.Monad.Monad' @(->) s@.\n--\n-- @\n-- 'ipreview' :: 'IndexedGetter' i s a     -> s -> 'Maybe' (i, a)\n-- 'ipreview' :: 'IndexedFold' i s a       -> s -> 'Maybe' (i, a)\n-- 'ipreview' :: 'IndexedLens'' i s a      -> s -> 'Maybe' (i, a)\n-- 'ipreview' :: 'IndexedTraversal'' i s a -> s -> 'Maybe' (i, a)\n-- @\n--\n-- However, it may be useful to think of its full generality when working with\n-- a 'Control.Monad.Monad' transformer stack:\n--\n-- @\n-- 'ipreview' :: 'MonadReader' s m => 'IndexedGetter' s a     -> m ('Maybe' (i, a))\n-- 'ipreview' :: 'MonadReader' s m => 'IndexedFold' s a       -> m ('Maybe' (i, a))\n-- 'ipreview' :: 'MonadReader' s m => 'IndexedLens'' s a      -> m ('Maybe' (i, a))\n-- 'ipreview' :: 'MonadReader' s m => 'IndexedTraversal'' s a -> m ('Maybe' (i, a))\n-- @\nipreview :: MonadReader s m => IndexedGetting i (First (i, a)) s a -> m (Maybe (i, a))\nipreview l = asks (getFirst #. ifoldMapOf l (\\i a -> First (Just (i, a))))\n{-# INLINE ipreview #-}\n\n-- | Retrieve a function of the first value targeted by a 'Fold' or\n-- 'Traversal' (or 'Just' the result from a 'Getter' or 'Lens').\n--\n-- This is usually applied in the 'Control.Monad.Reader.Reader'\n-- 'Control.Monad.Monad' @(->) s@.\n\n-- @\n-- 'previews' = 'views' '.' 'pre'\n-- @\n--\n-- @\n-- 'previews' :: 'Getter' s a     -> (a -> r) -> s -> 'Maybe' r\n-- 'previews' :: 'Fold' s a       -> (a -> r) -> s -> 'Maybe' r\n-- 'previews' :: 'Lens'' s a      -> (a -> r) -> s -> 'Maybe' r\n-- 'previews' :: 'Iso'' s a       -> (a -> r) -> s -> 'Maybe' r\n-- 'previews' :: 'Traversal'' s a -> (a -> r) -> s -> 'Maybe' r\n-- @\n--\n-- However, it may be useful to think of its full generality when working with\n-- a 'Monad' transformer stack:\n--\n-- @\n-- 'previews' :: 'MonadReader' s m => 'Getter' s a     -> (a -> r) -> m ('Maybe' r)\n-- 'previews' :: 'MonadReader' s m => 'Fold' s a       -> (a -> r) -> m ('Maybe' r)\n-- 'previews' :: 'MonadReader' s m => 'Lens'' s a      -> (a -> r) -> m ('Maybe' r)\n-- 'previews' :: 'MonadReader' s m => 'Iso'' s a       -> (a -> r) -> m ('Maybe' r)\n-- 'previews' :: 'MonadReader' s m => 'Traversal'' s a -> (a -> r) -> m ('Maybe' r)\n-- @\npreviews :: MonadReader s m => Getting (First r) s a -> (a -> r) -> m (Maybe r)\npreviews l f = asks (getFirst . foldMapOf l (First #. Just . f))\n{-# INLINE previews #-}\n\n-- | Retrieve a function of the first index and value targeted by an 'IndexedFold' or\n-- 'IndexedTraversal' (or 'Just' the result from an 'IndexedGetter' or 'IndexedLens').\n-- See also ('^@?').\n--\n-- @\n-- 'ipreviews' = 'views' '.' 'ipre'\n-- @\n--\n-- This is usually applied in the 'Control.Monad.Reader.Reader'\n-- 'Control.Monad.Monad' @(->) s@.\n--\n-- @\n-- 'ipreviews' :: 'IndexedGetter' i s a     -> (i -> a -> r) -> s -> 'Maybe' r\n-- 'ipreviews' :: 'IndexedFold' i s a       -> (i -> a -> r) -> s -> 'Maybe' r\n-- 'ipreviews' :: 'IndexedLens'' i s a      -> (i -> a -> r) -> s -> 'Maybe' r\n-- 'ipreviews' :: 'IndexedTraversal'' i s a -> (i -> a -> r) -> s -> 'Maybe' r\n-- @\n--\n-- However, it may be useful to think of its full generality when working with\n-- a 'Control.Monad.Monad' transformer stack:\n--\n-- @\n-- 'ipreviews' :: 'MonadReader' s m => 'IndexedGetter' i s a     -> (i -> a -> r) -> m ('Maybe' r)\n-- 'ipreviews' :: 'MonadReader' s m => 'IndexedFold' i s a       -> (i -> a -> r) -> m ('Maybe' r)\n-- 'ipreviews' :: 'MonadReader' s m => 'IndexedLens'' i s a      -> (i -> a -> r) -> m ('Maybe' r)\n-- 'ipreviews' :: 'MonadReader' s m => 'IndexedTraversal'' i s a -> (i -> a -> r) -> m ('Maybe' r)\n-- @\nipreviews :: MonadReader s m => IndexedGetting i (First r) s a -> (i -> a -> r) -> m (Maybe r)\nipreviews l f = asks (getFirst . ifoldMapOf l (\\i -> First #. Just . f i))\n{-# INLINE ipreviews #-}\n\n------------------------------------------------------------------------------\n-- Preuse\n------------------------------------------------------------------------------\n\n-- | Retrieve the first value targeted by a 'Fold' or 'Traversal' (or 'Just' the result\n-- from a 'Getter' or 'Lens') into the current state.\n--\n-- @\n-- 'preuse' = 'use' '.' 'pre'\n-- @\n--\n-- @\n-- 'preuse' :: 'MonadState' s m => 'Getter' s a     -> m ('Maybe' a)\n-- 'preuse' :: 'MonadState' s m => 'Fold' s a       -> m ('Maybe' a)\n-- 'preuse' :: 'MonadState' s m => 'Lens'' s a      -> m ('Maybe' a)\n-- 'preuse' :: 'MonadState' s m => 'Iso'' s a       -> m ('Maybe' a)\n-- 'preuse' :: 'MonadState' s m => 'Traversal'' s a -> m ('Maybe' a)\n-- @\npreuse :: MonadState s m => Getting (First a) s a -> m (Maybe a)\npreuse l = gets (preview l)\n{-# INLINE preuse #-}\n\n-- | Retrieve the first index and value targeted by an 'IndexedFold' or 'IndexedTraversal' (or 'Just' the index\n-- and result from an 'IndexedGetter' or 'IndexedLens') into the current state.\n--\n-- @\n-- 'ipreuse' = 'use' '.' 'ipre'\n-- @\n--\n-- @\n-- 'ipreuse' :: 'MonadState' s m => 'IndexedGetter' i s a     -> m ('Maybe' (i, a))\n-- 'ipreuse' :: 'MonadState' s m => 'IndexedFold' i s a       -> m ('Maybe' (i, a))\n-- 'ipreuse' :: 'MonadState' s m => 'IndexedLens'' i s a      -> m ('Maybe' (i, a))\n-- 'ipreuse' :: 'MonadState' s m => 'IndexedTraversal'' i s a -> m ('Maybe' (i, a))\n-- @\nipreuse :: MonadState s m => IndexedGetting i (First (i, a)) s a -> m (Maybe (i, a))\nipreuse l = gets (ipreview l)\n{-# INLINE ipreuse #-}\n\n-- | Retrieve a function of the first value targeted by a 'Fold' or\n-- 'Traversal' (or 'Just' the result from a 'Getter' or 'Lens') into the current state.\n--\n-- @\n-- 'preuses' = 'uses' '.' 'pre'\n-- @\n--\n-- @\n-- 'preuses' :: 'MonadState' s m => 'Getter' s a     -> (a -> r) -> m ('Maybe' r)\n-- 'preuses' :: 'MonadState' s m => 'Fold' s a       -> (a -> r) -> m ('Maybe' r)\n-- 'preuses' :: 'MonadState' s m => 'Lens'' s a      -> (a -> r) -> m ('Maybe' r)\n-- 'preuses' :: 'MonadState' s m => 'Iso'' s a       -> (a -> r) -> m ('Maybe' r)\n-- 'preuses' :: 'MonadState' s m => 'Traversal'' s a -> (a -> r) -> m ('Maybe' r)\n-- @\npreuses :: MonadState s m => Getting (First r) s a -> (a -> r) -> m (Maybe r)\npreuses l f = gets (previews l f)\n{-# INLINE preuses #-}\n\n-- | Retrieve a function of the first index and value targeted by an 'IndexedFold' or\n-- 'IndexedTraversal' (or a function of 'Just' the index and result from an 'IndexedGetter'\n-- or 'IndexedLens') into the current state.\n--\n-- @\n-- 'ipreuses' = 'uses' '.' 'ipre'\n-- @\n--\n-- @\n-- 'ipreuses' :: 'MonadState' s m => 'IndexedGetter' i s a     -> (i -> a -> r) -> m ('Maybe' r)\n-- 'ipreuses' :: 'MonadState' s m => 'IndexedFold' i s a       -> (i -> a -> r) -> m ('Maybe' r)\n-- 'ipreuses' :: 'MonadState' s m => 'IndexedLens'' i s a      -> (i -> a -> r) -> m ('Maybe' r)\n-- 'ipreuses' :: 'MonadState' s m => 'IndexedTraversal'' i s a -> (i -> a -> r) -> m ('Maybe' r)\n-- @\nipreuses :: MonadState s m => IndexedGetting i (First r) s a -> (i -> a -> r) -> m (Maybe r)\nipreuses l f = gets (ipreviews l f)\n{-# INLINE ipreuses #-}\n\n------------------------------------------------------------------------------\n-- Profunctors\n------------------------------------------------------------------------------\n\n\n-- | This allows you to 'Control.Traversable.traverse' the elements of a pretty much any 'LensLike' construction in the opposite order.\n--\n-- This will preserve indexes on 'Indexed' types and will give you the elements of a (finite) 'Fold' or 'Traversal' in the opposite order.\n--\n-- This has no practical impact on a 'Getter', 'Setter', 'Lens' or 'Iso'.\n--\n-- /NB:/ To write back through an 'Iso', you want to use 'Control.Lens.Isomorphic.from'.\n-- Similarly, to write back through an 'Prism', you want to use 'Control.Lens.Review.re'.\nbackwards :: (Profunctor p, Profunctor q) => Optical p q (Backwards f) s t a b -> Optical p q f s t a b\nbackwards l f = forwards #. l (Backwards #. f)\n{-# INLINE backwards #-}\n\n------------------------------------------------------------------------------\n-- Indexed Folds\n------------------------------------------------------------------------------\n\n-- | Fold an 'IndexedFold' or 'IndexedTraversal' by mapping indices and values to an arbitrary 'Monoid' with access\n-- to the @i@.\n--\n-- When you don't need access to the index then 'foldMapOf' is more flexible in what it accepts.\n--\n-- @\n-- 'foldMapOf' l \u2261 'ifoldMapOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'ifoldMapOf' ::             'IndexedGetter' i s a     -> (i -> a -> m) -> s -> m\n-- 'ifoldMapOf' :: 'Monoid' m => 'IndexedFold' i s a       -> (i -> a -> m) -> s -> m\n-- 'ifoldMapOf' ::             'IndexedLens'' i s a      -> (i -> a -> m) -> s -> m\n-- 'ifoldMapOf' :: 'Monoid' m => 'IndexedTraversal'' i s a -> (i -> a -> m) -> s -> m\n-- @\n--\nifoldMapOf :: IndexedGetting i m s a -> (i -> a -> m) -> s -> m\nifoldMapOf = coerce\n{-# INLINE ifoldMapOf #-}\n\n-- | Right-associative fold of parts of a structure that are viewed through an 'IndexedFold' or 'IndexedTraversal' with\n-- access to the @i@.\n--\n-- When you don't need access to the index then 'foldrOf' is more flexible in what it accepts.\n--\n-- @\n-- 'foldrOf' l \u2261 'ifoldrOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'ifoldrOf' :: 'IndexedGetter' i s a     -> (i -> a -> r -> r) -> r -> s -> r\n-- 'ifoldrOf' :: 'IndexedFold' i s a       -> (i -> a -> r -> r) -> r -> s -> r\n-- 'ifoldrOf' :: 'IndexedLens'' i s a      -> (i -> a -> r -> r) -> r -> s -> r\n-- 'ifoldrOf' :: 'IndexedTraversal'' i s a -> (i -> a -> r -> r) -> r -> s -> r\n-- @\nifoldrOf :: IndexedGetting i (Endo r) s a -> (i -> a -> r -> r) -> r -> s -> r\nifoldrOf l f z = flip appEndo z . getConst #. l (Const #. Endo #. Indexed f)\n{-# INLINE ifoldrOf #-}\n\n-- | Left-associative fold of the parts of a structure that are viewed through an 'IndexedFold' or 'IndexedTraversal' with\n-- access to the @i@.\n--\n-- When you don't need access to the index then 'foldlOf' is more flexible in what it accepts.\n--\n-- @\n-- 'foldlOf' l \u2261 'ifoldlOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'ifoldlOf' :: 'IndexedGetter' i s a     -> (i -> r -> a -> r) -> r -> s -> r\n-- 'ifoldlOf' :: 'IndexedFold' i s a       -> (i -> r -> a -> r) -> r -> s -> r\n-- 'ifoldlOf' :: 'IndexedLens'' i s a      -> (i -> r -> a -> r) -> r -> s -> r\n-- 'ifoldlOf' :: 'IndexedTraversal'' i s a -> (i -> r -> a -> r) -> r -> s -> r\n-- @\nifoldlOf :: IndexedGetting i (Dual (Endo r)) s a -> (i -> r -> a -> r) -> r -> s -> r\nifoldlOf l f z = (flip appEndo z .# getDual) `rmap` ifoldMapOf l (\\i -> Dual #. Endo #. flip (f i))\n{-# INLINE ifoldlOf #-}\n\n-- | Return whether or not any element viewed through an 'IndexedFold' or 'IndexedTraversal'\n-- satisfy a predicate, with access to the @i@.\n--\n-- When you don't need access to the index then 'anyOf' is more flexible in what it accepts.\n--\n-- @\n-- 'anyOf' l \u2261 'ianyOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'ianyOf' :: 'IndexedGetter' i s a     -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- 'ianyOf' :: 'IndexedFold' i s a       -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- 'ianyOf' :: 'IndexedLens'' i s a      -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- 'ianyOf' :: 'IndexedTraversal'' i s a -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- @\nianyOf :: IndexedGetting i Any s a -> (i -> a -> Bool) -> s -> Bool\nianyOf = coerce\n{-# INLINE ianyOf #-}\n\n-- | Return whether or not all elements viewed through an 'IndexedFold' or 'IndexedTraversal'\n-- satisfy a predicate, with access to the @i@.\n--\n-- When you don't need access to the index then 'allOf' is more flexible in what it accepts.\n--\n-- @\n-- 'allOf' l \u2261 'iallOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'iallOf' :: 'IndexedGetter' i s a     -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- 'iallOf' :: 'IndexedFold' i s a       -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- 'iallOf' :: 'IndexedLens'' i s a      -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- 'iallOf' :: 'IndexedTraversal'' i s a -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- @\niallOf :: IndexedGetting i All s a -> (i -> a -> Bool) -> s -> Bool\niallOf = coerce\n{-# INLINE iallOf #-}\n\n-- | Return whether or not none of the elements viewed through an 'IndexedFold' or 'IndexedTraversal'\n-- satisfy a predicate, with access to the @i@.\n--\n-- When you don't need access to the index then 'noneOf' is more flexible in what it accepts.\n--\n-- @\n-- 'noneOf' l \u2261 'inoneOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'inoneOf' :: 'IndexedGetter' i s a     -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- 'inoneOf' :: 'IndexedFold' i s a       -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- 'inoneOf' :: 'IndexedLens'' i s a      -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- 'inoneOf' :: 'IndexedTraversal'' i s a -> (i -> a -> 'Bool') -> s -> 'Bool'\n-- @\ninoneOf :: IndexedGetting i Any s a -> (i -> a -> Bool) -> s -> Bool\ninoneOf l f = not . ianyOf l f\n{-# INLINE inoneOf #-}\n\n-- | Traverse the targets of an 'IndexedFold' or 'IndexedTraversal' with access to the @i@, discarding the results.\n--\n-- When you don't need access to the index then 'traverseOf_' is more flexible in what it accepts.\n--\n-- @\n-- 'traverseOf_' l \u2261 'Control.Lens.Traversal.itraverseOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'itraverseOf_' :: 'Functor' f     => 'IndexedGetter' i s a     -> (i -> a -> f r) -> s -> f ()\n-- 'itraverseOf_' :: 'Applicative' f => 'IndexedFold' i s a       -> (i -> a -> f r) -> s -> f ()\n-- 'itraverseOf_' :: 'Functor' f     => 'IndexedLens'' i s a      -> (i -> a -> f r) -> s -> f ()\n-- 'itraverseOf_' :: 'Applicative' f => 'IndexedTraversal'' i s a -> (i -> a -> f r) -> s -> f ()\n-- @\nitraverseOf_ :: Functor f => IndexedGetting i (Traversed r f) s a -> (i -> a -> f r) -> s -> f ()\nitraverseOf_ l f = void . getTraversed #. getConst #. l (Const #. Traversed #. Indexed f)\n{-# INLINE itraverseOf_ #-}\n\n-- | Traverse the targets of an 'IndexedFold' or 'IndexedTraversal' with access to the index, discarding the results\n-- (with the arguments flipped).\n--\n-- @\n-- 'iforOf_' \u2261 'flip' '.' 'itraverseOf_'\n-- @\n--\n-- When you don't need access to the index then 'forOf_' is more flexible in what it accepts.\n--\n-- @\n-- 'forOf_' l a \u2261 'iforOf_' l a '.' 'const'\n-- @\n--\n-- @\n-- 'iforOf_' :: 'Functor' f     => 'IndexedGetter' i s a     -> s -> (i -> a -> f r) -> f ()\n-- 'iforOf_' :: 'Applicative' f => 'IndexedFold' i s a       -> s -> (i -> a -> f r) -> f ()\n-- 'iforOf_' :: 'Functor' f     => 'IndexedLens'' i s a      -> s -> (i -> a -> f r) -> f ()\n-- 'iforOf_' :: 'Applicative' f => 'IndexedTraversal'' i s a -> s -> (i -> a -> f r) -> f ()\n-- @\niforOf_ :: Functor f => IndexedGetting i (Traversed r f) s a -> s -> (i -> a -> f r) -> f ()\niforOf_ = flip . itraverseOf_\n{-# INLINE iforOf_ #-}\n\n-- | Run monadic actions for each target of an 'IndexedFold' or 'IndexedTraversal' with access to the index,\n-- discarding the results.\n--\n-- When you don't need access to the index then 'mapMOf_' is more flexible in what it accepts.\n--\n-- @\n-- 'mapMOf_' l \u2261 'Control.Lens.Setter.imapMOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'imapMOf_' :: 'Monad' m => 'IndexedGetter' i s a     -> (i -> a -> m r) -> s -> m ()\n-- 'imapMOf_' :: 'Monad' m => 'IndexedFold' i s a       -> (i -> a -> m r) -> s -> m ()\n-- 'imapMOf_' :: 'Monad' m => 'IndexedLens'' i s a      -> (i -> a -> m r) -> s -> m ()\n-- 'imapMOf_' :: 'Monad' m => 'IndexedTraversal'' i s a -> (i -> a -> m r) -> s -> m ()\n-- @\nimapMOf_ :: Monad m => IndexedGetting i (Sequenced r m) s a -> (i -> a -> m r) -> s -> m ()\nimapMOf_ l f = liftM skip . getSequenced #. getConst #. l (Const #. Sequenced #. Indexed f)\n{-# INLINE imapMOf_ #-}\n\n-- | Run monadic actions for each target of an 'IndexedFold' or 'IndexedTraversal' with access to the index,\n-- discarding the results (with the arguments flipped).\n--\n-- @\n-- 'iforMOf_' \u2261 'flip' '.' 'imapMOf_'\n-- @\n--\n-- When you don't need access to the index then 'forMOf_' is more flexible in what it accepts.\n--\n-- @\n-- 'forMOf_' l a \u2261 'Control.Lens.Traversal.iforMOf' l a '.' 'const'\n-- @\n--\n-- @\n-- 'iforMOf_' :: 'Monad' m => 'IndexedGetter' i s a     -> s -> (i -> a -> m r) -> m ()\n-- 'iforMOf_' :: 'Monad' m => 'IndexedFold' i s a       -> s -> (i -> a -> m r) -> m ()\n-- 'iforMOf_' :: 'Monad' m => 'IndexedLens'' i s a      -> s -> (i -> a -> m r) -> m ()\n-- 'iforMOf_' :: 'Monad' m => 'IndexedTraversal'' i s a -> s -> (i -> a -> m r) -> m ()\n-- @\niforMOf_ :: Monad m => IndexedGetting i (Sequenced r m) s a -> s -> (i -> a -> m r) -> m ()\niforMOf_ = flip . imapMOf_\n{-# INLINE iforMOf_ #-}\n\n-- | Concatenate the results of a function of the elements of an 'IndexedFold' or 'IndexedTraversal'\n-- with access to the index.\n--\n-- When you don't need access to the index then 'concatMapOf'  is more flexible in what it accepts.\n--\n-- @\n-- 'concatMapOf' l \u2261 'iconcatMapOf' l '.' 'const'\n-- 'iconcatMapOf' \u2261 'ifoldMapOf'\n-- @\n--\n-- @\n-- 'iconcatMapOf' :: 'IndexedGetter' i s a     -> (i -> a -> [r]) -> s -> [r]\n-- 'iconcatMapOf' :: 'IndexedFold' i s a       -> (i -> a -> [r]) -> s -> [r]\n-- 'iconcatMapOf' :: 'IndexedLens'' i s a      -> (i -> a -> [r]) -> s -> [r]\n-- 'iconcatMapOf' :: 'IndexedTraversal'' i s a -> (i -> a -> [r]) -> s -> [r]\n-- @\niconcatMapOf :: IndexedGetting i [r] s a -> (i -> a -> [r]) -> s -> [r]\niconcatMapOf = ifoldMapOf\n{-# INLINE iconcatMapOf #-}\n\n-- | The 'ifindOf' function takes an 'IndexedFold' or 'IndexedTraversal', a predicate that is also\n-- supplied the index, a structure and returns the left-most element of the structure\n-- matching the predicate, or 'Nothing' if there is no such element.\n--\n-- When you don't need access to the index then 'findOf' is more flexible in what it accepts.\n--\n-- @\n-- 'findOf' l \u2261 'ifindOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'ifindOf' :: 'IndexedGetter' i s a     -> (i -> a -> 'Bool') -> s -> 'Maybe' a\n-- 'ifindOf' :: 'IndexedFold' i s a       -> (i -> a -> 'Bool') -> s -> 'Maybe' a\n-- 'ifindOf' :: 'IndexedLens'' i s a      -> (i -> a -> 'Bool') -> s -> 'Maybe' a\n-- 'ifindOf' :: 'IndexedTraversal'' i s a -> (i -> a -> 'Bool') -> s -> 'Maybe' a\n-- @\nifindOf :: IndexedGetting i (Endo (Maybe a)) s a -> (i -> a -> Bool) -> s -> Maybe a\nifindOf l f = ifoldrOf l (\\i a y -> if f i a then Just a else y) Nothing\n{-# INLINE ifindOf #-}\n\n-- | The 'ifindMOf' function takes an 'IndexedFold' or 'IndexedTraversal', a monadic predicate that is also\n-- supplied the index, a structure and returns in the monad the left-most element of the structure\n-- matching the predicate, or 'Nothing' if there is no such element.\n--\n-- When you don't need access to the index then 'findMOf' is more flexible in what it accepts.\n--\n-- @\n-- 'findMOf' l \u2261 'ifindMOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'ifindMOf' :: 'Monad' m => 'IndexedGetter' i s a     -> (i -> a -> m 'Bool') -> s -> m ('Maybe' a)\n-- 'ifindMOf' :: 'Monad' m => 'IndexedFold' i s a       -> (i -> a -> m 'Bool') -> s -> m ('Maybe' a)\n-- 'ifindMOf' :: 'Monad' m => 'IndexedLens'' i s a      -> (i -> a -> m 'Bool') -> s -> m ('Maybe' a)\n-- 'ifindMOf' :: 'Monad' m => 'IndexedTraversal'' i s a -> (i -> a -> m 'Bool') -> s -> m ('Maybe' a)\n-- @\nifindMOf :: Monad m => IndexedGetting i (Endo (m (Maybe a))) s a -> (i -> a -> m Bool) -> s -> m (Maybe a)\nifindMOf l f = ifoldrOf l (\\i a y -> f i a >>= \\r -> if r then return (Just a) else y) $ return Nothing\n{-# INLINE ifindMOf #-}\n\n-- | /Strictly/ fold right over the elements of a structure with an index.\n--\n-- When you don't need access to the index then 'foldrOf'' is more flexible in what it accepts.\n--\n-- @\n-- 'foldrOf'' l \u2261 'ifoldrOf'' l '.' 'const'\n-- @\n--\n-- @\n-- 'ifoldrOf'' :: 'IndexedGetter' i s a     -> (i -> a -> r -> r) -> r -> s -> r\n-- 'ifoldrOf'' :: 'IndexedFold' i s a       -> (i -> a -> r -> r) -> r -> s -> r\n-- 'ifoldrOf'' :: 'IndexedLens'' i s a      -> (i -> a -> r -> r) -> r -> s -> r\n-- 'ifoldrOf'' :: 'IndexedTraversal'' i s a -> (i -> a -> r -> r) -> r -> s -> r\n-- @\nifoldrOf' :: IndexedGetting i (Dual (Endo (r -> r))) s a -> (i -> a -> r -> r) -> r -> s -> r\nifoldrOf' l f z0 xs = ifoldlOf l f' id xs z0\n  where f' i k x z = k $! f i x z\n{-# INLINE ifoldrOf' #-}\n\n-- | Fold over the elements of a structure with an index, associating to the left, but /strictly/.\n--\n-- When you don't need access to the index then 'foldlOf'' is more flexible in what it accepts.\n--\n-- @\n-- 'foldlOf'' l \u2261 'ifoldlOf'' l '.' 'const'\n-- @\n--\n-- @\n-- 'ifoldlOf'' :: 'IndexedGetter' i s a       -> (i -> r -> a -> r) -> r -> s -> r\n-- 'ifoldlOf'' :: 'IndexedFold' i s a         -> (i -> r -> a -> r) -> r -> s -> r\n-- 'ifoldlOf'' :: 'IndexedLens'' i s a        -> (i -> r -> a -> r) -> r -> s -> r\n-- 'ifoldlOf'' :: 'IndexedTraversal'' i s a   -> (i -> r -> a -> r) -> r -> s -> r\n-- @\nifoldlOf' :: IndexedGetting i (Endo (r -> r)) s a -> (i -> r -> a -> r) -> r -> s -> r\nifoldlOf' l f z0 xs = ifoldrOf l f' id xs z0\n  where f' i x k z = k $! f i z x\n{-# INLINE ifoldlOf' #-}\n\n-- | Monadic fold right over the elements of a structure with an index.\n--\n-- When you don't need access to the index then 'foldrMOf' is more flexible in what it accepts.\n--\n-- @\n-- 'foldrMOf' l \u2261 'ifoldrMOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'ifoldrMOf' :: 'Monad' m => 'IndexedGetter' i s a     -> (i -> a -> r -> m r) -> r -> s -> m r\n-- 'ifoldrMOf' :: 'Monad' m => 'IndexedFold' i s a       -> (i -> a -> r -> m r) -> r -> s -> m r\n-- 'ifoldrMOf' :: 'Monad' m => 'IndexedLens'' i s a      -> (i -> a -> r -> m r) -> r -> s -> m r\n-- 'ifoldrMOf' :: 'Monad' m => 'IndexedTraversal'' i s a -> (i -> a -> r -> m r) -> r -> s -> m r\n-- @\nifoldrMOf :: Monad m => IndexedGetting i (Dual (Endo (r -> m r))) s a -> (i -> a -> r -> m r) -> r -> s -> m r\nifoldrMOf l f z0 xs = ifoldlOf l f' return xs z0\n  where f' i k x z = f i x z >>= k\n{-# INLINE ifoldrMOf #-}\n\n-- | Monadic fold over the elements of a structure with an index, associating to the left.\n--\n-- When you don't need access to the index then 'foldlMOf' is more flexible in what it accepts.\n--\n-- @\n-- 'foldlMOf' l \u2261 'ifoldlMOf' l '.' 'const'\n-- @\n--\n-- @\n-- 'ifoldlMOf' :: 'Monad' m => 'IndexedGetter' i s a     -> (i -> r -> a -> m r) -> r -> s -> m r\n-- 'ifoldlMOf' :: 'Monad' m => 'IndexedFold' i s a       -> (i -> r -> a -> m r) -> r -> s -> m r\n-- 'ifoldlMOf' :: 'Monad' m => 'IndexedLens'' i s a      -> (i -> r -> a -> m r) -> r -> s -> m r\n-- 'ifoldlMOf' :: 'Monad' m => 'IndexedTraversal'' i s a -> (i -> r -> a -> m r) -> r -> s -> m r\n-- @\nifoldlMOf :: Monad m => IndexedGetting i (Endo (r -> m r)) s a -> (i -> r -> a -> m r) -> r -> s -> m r\nifoldlMOf l f z0 xs = ifoldrOf l f' return xs z0\n  where f' i x k z = f i z x >>= k\n{-# INLINE ifoldlMOf #-}\n\n-- | Extract the key-value pairs from a structure.\n--\n-- When you don't need access to the indices in the result, then 'toListOf' is more flexible in what it accepts.\n--\n-- @\n-- 'toListOf' l \u2261 'map' 'snd' '.' 'itoListOf' l\n-- @\n--\n-- @\n-- 'itoListOf' :: 'IndexedGetter' i s a     -> s -> [(i,a)]\n-- 'itoListOf' :: 'IndexedFold' i s a       -> s -> [(i,a)]\n-- 'itoListOf' :: 'IndexedLens'' i s a      -> s -> [(i,a)]\n-- 'itoListOf' :: 'IndexedTraversal'' i s a -> s -> [(i,a)]\n-- @\nitoListOf :: IndexedGetting i (Endo [(i,a)]) s a -> s -> [(i,a)]\nitoListOf l = ifoldrOf l (\\i a -> ((i,a):)) []\n{-# INLINE itoListOf #-}\n\n-- | An infix version of 'itoListOf'.\n\n-- @\n-- ('^@..') :: s -> 'IndexedGetter' i s a     -> [(i,a)]\n-- ('^@..') :: s -> 'IndexedFold' i s a       -> [(i,a)]\n-- ('^@..') :: s -> 'IndexedLens'' i s a      -> [(i,a)]\n-- ('^@..') :: s -> 'IndexedTraversal'' i s a -> [(i,a)]\n-- @\n(^@..) :: s -> IndexedGetting i (Endo [(i,a)]) s a -> [(i,a)]\ns ^@.. l = ifoldrOf l (\\i a -> ((i,a):)) [] s\n{-# INLINE (^@..) #-}\n\n-- | Perform a safe 'head' (with index) of an 'IndexedFold' or 'IndexedTraversal' or retrieve 'Just' the index and result\n-- from an 'IndexedGetter' or 'IndexedLens'.\n--\n-- When using a 'IndexedTraversal' as a partial 'IndexedLens', or an 'IndexedFold' as a partial 'IndexedGetter' this can be a convenient\n-- way to extract the optional value.\n--\n-- @\n-- ('^@?') :: s -> 'IndexedGetter' i s a     -> 'Maybe' (i, a)\n-- ('^@?') :: s -> 'IndexedFold' i s a       -> 'Maybe' (i, a)\n-- ('^@?') :: s -> 'IndexedLens'' i s a      -> 'Maybe' (i, a)\n-- ('^@?') :: s -> 'IndexedTraversal'' i s a -> 'Maybe' (i, a)\n-- @\n(^@?) :: s -> IndexedGetting i (Endo (Maybe (i, a))) s a -> Maybe (i, a)\ns ^@? l = ifoldrOf l (\\i x _ -> Just (i,x)) Nothing s\n{-# INLINE (^@?) #-}\n\n-- | Perform an *UNSAFE* 'head' (with index) of an 'IndexedFold' or 'IndexedTraversal' assuming that it is there.\n--\n-- @\n-- ('^@?!') :: s -> 'IndexedGetter' i s a     -> (i, a)\n-- ('^@?!') :: s -> 'IndexedFold' i s a       -> (i, a)\n-- ('^@?!') :: s -> 'IndexedLens'' i s a      -> (i, a)\n-- ('^@?!') :: s -> 'IndexedTraversal'' i s a -> (i, a)\n-- @\n(^@?!) :: HasCallStack => s -> IndexedGetting i (Endo (i, a)) s a -> (i, a)\ns ^@?! l = ifoldrOf l (\\i x _ -> (i,x)) (error \"(^@?!): empty Fold\") s\n{-# INLINE (^@?!) #-}\n\n-- | Retrieve the index of the first value targeted by a 'IndexedFold' or 'IndexedTraversal' which is equal to a given value.\n--\n-- @\n-- 'Data.List.elemIndex' \u2261 'elemIndexOf' 'folded'\n-- @\n--\n-- @\n-- 'elemIndexOf' :: 'Eq' a => 'IndexedFold' i s a       -> a -> s -> 'Maybe' i\n-- 'elemIndexOf' :: 'Eq' a => 'IndexedTraversal'' i s a -> a -> s -> 'Maybe' i\n-- @\nelemIndexOf :: Eq a => IndexedGetting i (First i) s a -> a -> s -> Maybe i\nelemIndexOf l a = findIndexOf l (a ==)\n{-# INLINE elemIndexOf #-}\n\n-- | Retrieve the indices of the values targeted by a 'IndexedFold' or 'IndexedTraversal' which are equal to a given value.\n--\n-- @\n-- 'Data.List.elemIndices' \u2261 'elemIndicesOf' 'folded'\n-- @\n--\n-- @\n-- 'elemIndicesOf' :: 'Eq' a => 'IndexedFold' i s a       -> a -> s -> [i]\n-- 'elemIndicesOf' :: 'Eq' a => 'IndexedTraversal'' i s a -> a -> s -> [i]\n-- @\nelemIndicesOf :: Eq a => IndexedGetting i (Endo [i]) s a -> a -> s -> [i]\nelemIndicesOf l a = findIndicesOf l (a ==)\n{-# INLINE elemIndicesOf #-}\n\n-- | Retrieve the index of the first value targeted by a 'IndexedFold' or 'IndexedTraversal' which satisfies a predicate.\n--\n-- @\n-- 'Data.List.findIndex' \u2261 'findIndexOf' 'folded'\n-- @\n--\n-- @\n-- 'findIndexOf' :: 'IndexedFold' i s a       -> (a -> 'Bool') -> s -> 'Maybe' i\n-- 'findIndexOf' :: 'IndexedTraversal'' i s a -> (a -> 'Bool') -> s -> 'Maybe' i\n-- @\nfindIndexOf :: IndexedGetting i (First i) s a -> (a -> Bool) -> s -> Maybe i\nfindIndexOf l p = preview (l . filtered p . asIndex)\n{-# INLINE findIndexOf #-}\n\n-- | Retrieve the indices of the values targeted by a 'IndexedFold' or 'IndexedTraversal' which satisfy a predicate.\n--\n-- @\n-- 'Data.List.findIndices' \u2261 'findIndicesOf' 'folded'\n-- @\n--\n-- @\n-- 'findIndicesOf' :: 'IndexedFold' i s a       -> (a -> 'Bool') -> s -> [i]\n-- 'findIndicesOf' :: 'IndexedTraversal'' i s a -> (a -> 'Bool') -> s -> [i]\n-- @\nfindIndicesOf :: IndexedGetting i (Endo [i]) s a -> (a -> Bool) -> s -> [i]\nfindIndicesOf l p = toListOf (l . filtered p . asIndex)\n{-# INLINE findIndicesOf #-}\n\n-------------------------------------------------------------------------------\n-- Converting to Folds\n-------------------------------------------------------------------------------\n\n-- | Filter an 'IndexedFold' or 'IndexedGetter', obtaining an 'IndexedFold'.\n--\n-- >>> [0,0,0,5,5,5]^..traversed.ifiltered (\\i a -> i <= a)\n-- [0,5,5,5]\n--\n-- Compose with 'ifiltered' to filter another 'IndexedLens', 'IndexedIso', 'IndexedGetter', 'IndexedFold' (or 'IndexedTraversal') with\n-- access to both the value and the index.\n--\n-- Note: As with 'filtered', this is /not/ a legal 'IndexedTraversal', unless you are very careful not to invalidate the predicate on the target!\nifiltered :: (Indexable i p, Applicative f) => (i -> a -> Bool) -> Optical' p (Indexed i) f a a\nifiltered p f = Indexed $ \\i a -> if p i a then indexed f i a else pure a\n{-# INLINE ifiltered #-}\n\n-- | Obtain an 'IndexedFold' by taking elements from another\n-- 'IndexedFold', 'IndexedLens', 'IndexedGetter' or 'IndexedTraversal' while a predicate holds.\n--\n-- @\n-- 'itakingWhile' :: (i -> a -> 'Bool') -> 'IndexedFold' i s a          -> 'IndexedFold' i s a\n-- 'itakingWhile' :: (i -> a -> 'Bool') -> 'IndexedTraversal'' i s a    -> 'IndexedFold' i s a\n-- 'itakingWhile' :: (i -> a -> 'Bool') -> 'IndexedLens'' i s a         -> 'IndexedFold' i s a\n-- 'itakingWhile' :: (i -> a -> 'Bool') -> 'IndexedGetter' i s a        -> 'IndexedFold' i s a\n-- @\n--\n-- Note: Applying 'itakingWhile' to an 'IndexedLens' or 'IndexedTraversal' will still allow you to use it as a\n-- pseudo-'IndexedTraversal', but if you change the value of any target to one where the predicate returns\n-- 'False', then you will break the 'Traversal' laws and 'Traversal' fusion will no longer be sound.\nitakingWhile :: (Indexable i p, Profunctor q, Contravariant f, Applicative f)\n         => (i -> a -> Bool)\n         -> Optical' (Indexed i) q (Const (Endo (f s))) s a\n         -> Optical' p q f s a\nitakingWhile p l f = (flip appEndo noEffect .# getConst) `rmap` l g where\n  g = Indexed $ \\i a -> Const . Endo $ if p i a then (indexed f i a *>) else const noEffect\n{-# INLINE itakingWhile #-}\n\n-- | Obtain an 'IndexedFold' by dropping elements from another 'IndexedFold', 'IndexedLens', 'IndexedGetter' or 'IndexedTraversal' while a predicate holds.\n--\n-- @\n-- 'idroppingWhile' :: (i -> a -> 'Bool') -> 'IndexedFold' i s a          -> 'IndexedFold' i s a\n-- 'idroppingWhile' :: (i -> a -> 'Bool') -> 'IndexedTraversal'' i s a    -> 'IndexedFold' i s a -- see notes\n-- 'idroppingWhile' :: (i -> a -> 'Bool') -> 'IndexedLens'' i s a         -> 'IndexedFold' i s a -- see notes\n-- 'idroppingWhile' :: (i -> a -> 'Bool') -> 'IndexedGetter' i s a        -> 'IndexedFold' i s a\n-- @\n--\n-- Note: As with `droppingWhile` applying 'idroppingWhile' to an 'IndexedLens' or 'IndexedTraversal' will still\n-- allow you to use it as a pseudo-'IndexedTraversal', but if you change the value of the first target to one\n-- where the predicate returns 'True', then you will break the 'Traversal' laws and 'Traversal' fusion will\n-- no longer be sound.\nidroppingWhile :: (Indexable i p, Profunctor q, Applicative f)\n              => (i -> a -> Bool)\n              -> Optical (Indexed i) q (Compose (State Bool) f) s t a a\n              -> Optical p q f s t a a\nidroppingWhile p l f = (flip evalState True .# getCompose) `rmap` l g where\n  g = Indexed $ \\ i a -> Compose $ state $ \\b -> let\n      b' = b && p i a\n    in (if b' then pure a else indexed f i a, b')\n{-# INLINE idroppingWhile #-}\n\n------------------------------------------------------------------------------\n-- Misc.\n------------------------------------------------------------------------------\n\nskip :: a -> ()\nskip _ = ()\n{-# INLINE skip #-}\n\nnoEffect = undefined\n\ncollect = undefined\n\napDefault = undefined\n\nswap = undefined\n", "meta": {"hexsha": "4e0be9cbd0ce35a8e660a09988a374412fa4c852", "size": 189638, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "testsuite/tests/haddock/perf/Fold.hs", "max_stars_repo_name": "hexresearch/ghc", "max_stars_repo_head_hexsha": "5ff690b8474c74e9c968ef31e568c1ad0fe719a1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-30T07:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T07:57:24.000Z", "max_issues_repo_path": "testsuite/tests/haddock/perf/Fold.hs", "max_issues_repo_name": "hexresearch/ghc", "max_issues_repo_head_hexsha": "5ff690b8474c74e9c968ef31e568c1ad0fe719a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testsuite/tests/haddock/perf/Fold.hs", "max_forks_repo_name": "hexresearch/ghc", "max_forks_repo_head_hexsha": "5ff690b8474c74e9c968ef31e568c1ad0fe719a1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5743490839, "max_line_length": 188, "alphanum_fraction": 0.5442210949, "num_tokens": 61906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.19758570929427727}}
{"text": "-- |\n-- Module      : Jeopardy.Graphics\n-- Description : Rendering functionality for the Jeopardy game\n-- Copyright   : (c) Jonatan H Sundqvist, 2015\n-- License     : MIT\n-- Maintainer  : Jonatan H Sundqvist\n-- Stability   : experimental|stable\n-- Portability : POSIX (not sure)\n-- \n\n-- Created July 7 2015\n\n-- TODO | - 'App' type with configurations, event listeners, etc.\n--        - \n\n-- SPEC | -\n--        -\n\n\n\nmodule Jeopardy.Graphics where\n\n\n\n---------------------------------------------------------------------------------------------------\n-- We'll need these\n---------------------------------------------------------------------------------------------------\nimport qualified Graphics.Rendering.Cairo as Cairo --\n\nimport Control.Monad (when, forM_) --\nimport Data.Complex\n\nimport qualified Southpaw.Picasso.Palette as Palette --\nimport Southpaw.Picasso.RenderUtils                  --\n\nimport Jeopardy.Core --\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Types\n---------------------------------------------------------------------------------------------------\ntype Point = Complex Double\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Data\n---------------------------------------------------------------------------------------------------\n\u03c0 = pi\n\u03c4 = 2*\u03c0\n\n\n\n---------------------------------------------------------------------------------------------------\n-- Functions\n---------------------------------------------------------------------------------------------------\n-- Game specific rendering ------------------------------------------------------------------------\n-- |\nrenderGame :: Game -> Cairo.Render ()\nrenderGame game = do\n\t--\n\tlet (dx, padx) = (42, 5)\n\tmapM_ (\\ (n, cat) -> renderCategory ((50+n*(dx+padx)*2):+50) (dx:+dx) 4 cat) . zip [1..] $ _board game\n\n\n-- |\nrenderAnswerTile :: Point -> Double -> String -> Cairo.Render ()\nrenderAnswerTile (cx:+cy) radius answer = do\n\tCairo.arc cx cy radius 0 \u03c4\n\tPalette.choose Palette.blue\n\tCairo.fill\n\n\tCairo.arc cx cy (radius*0.86) 0 \u03c4\n\tPalette.choose Palette.cadetblue\n\tCairo.fill\n\n\tPalette.choose Palette.black\n\tCairo.setFontSize 18\n\trenderCentredText (cx:+cy) answer\n\n\n-- |\nrenderCategoryHeading :: Point -> Point -> String -> Cairo.Render ()\nrenderCategoryHeading (cx:+cy) (dx:+dy) title = do\n\tCairo.rectangle (cx-dx) (cy-dy) (dx*2) (dy*2)\n\tPalette.choose Palette.blue\n\tCairo.fill\n\n\tCairo.rectangle (cx-(dx*0.86)) (cy-(dy*0.86)) (dx*2*0.86) (dy*2*0.86)\n\tPalette.choose Palette.cadetblue\n\tCairo.fill\n\n\tPalette.choose Palette.black\n\tCairo.setFontSize 18\n\trenderCentredText (cx:+cy) title\n\n\n-- |\n-- TODO: Add layout option parameters\nrenderCategory :: Point -> Point -> Double -> Category -> Cairo.Render ()\nrenderCategory (cx:+cy) (dx:+dy) pady (Category { _questions=q, _title=t }) = do\n\trenderCategoryHeading (cx:+cy) (dx:+(dy*0.8)) t\n\tmapM_ (\\ (n, q) -> renderAnswerTile (cx:+(cy+n*(dy+pady)*2)) dx . show $ _value q) . zip [1..] $ q\n\n\n-- General rendering utilities --------------------------------------------------------------------\n-- |\nrenderCircle :: Double -> Point -> Cairo.Render ()\nrenderCircle radius (cx:+cy) = Cairo.arc cx cy radius 0 \u03c4\n\n\n---------------------------------------------------------------------------------------------------\n", "meta": {"hexsha": "c0fd004946ce842d094b0b9b879fb4a838e423d6", "size": 3343, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Jeopardy/Graphics.hs", "max_stars_repo_name": "SwiftsNamesake/Leopardy", "max_stars_repo_head_hexsha": "27de74fe64fa3b131c35b8a6a6ddfb2d60db658b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Jeopardy/Graphics.hs", "max_issues_repo_name": "SwiftsNamesake/Leopardy", "max_issues_repo_head_hexsha": "27de74fe64fa3b131c35b8a6a6ddfb2d60db658b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Jeopardy/Graphics.hs", "max_forks_repo_name": "SwiftsNamesake/Leopardy", "max_forks_repo_head_hexsha": "27de74fe64fa3b131c35b8a6a6ddfb2d60db658b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3245614035, "max_line_length": 103, "alphanum_fraction": 0.457672749, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.19733961646643522}}
{"text": "-- |\n-- Module      : Occlusion.Render\n-- Description :\n-- Copyright   : (c) Jonatan H Sundqvist, 2015\n-- License     : MIT\n-- Maintainer  : Jonatan H Sundqvist\n-- Stability   : experimental|stable\n-- Portability : POSIX (not sure)\n--\n\n-- Created September 21 2015\n\n-- TODO | - Move generally useful functions to library (eg. Southpaw)\n--        -\n\n-- SPEC | -\n--        -\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- GHC Pragmas\n--------------------------------------------------------------------------------------------------------------------------------------------\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- API\n--------------------------------------------------------------------------------------------------------------------------------------------\nmodule Occlusion.Render where\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- We'll need these\n--------------------------------------------------------------------------------------------------------------------------------------------\nimport Data.Complex\nimport Data.IORef\nimport Data.Functor\nimport Data.Function\nimport Control.Monad (forM, forM_, mapM, mapM_, when, unless, void)\nimport Control.Lens\nimport Text.Printf\n\nimport qualified Data.Map as M\n\nimport qualified Graphics.Rendering.Cairo as Cairo\n\nimport           Southpaw.Math.Trigonometry\nimport           Southpaw.Math.Constants\nimport           Southpaw.Picasso.RenderUtils hiding (vectorise)\nimport qualified Southpaw.Picasso.Render  as Render\nimport qualified Southpaw.Picasso.Palette as Palette\n\nimport Occlusion.Types\nimport Occlusion.Lenses\nimport Occlusion.Vector\nimport qualified Occlusion.Core as Core\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- Functions\n--------------------------------------------------------------------------------------------------------------------------------------------\n-- |\nscene :: Scene -> Cairo.Render ()\nscene thescene = do\n  -- Render obstacles\n  forM (thescene^.obstacles) $ \\poly -> do\n    polygon poly\n    Cairo.setSourceRGBA 0.96 0.67 0.02 1.00\n    Cairo.fill\n    -- polygonDebug (thescene^.player.position) poly\n\n  -- Render span lines\n  -- forM (thescene^.obstacles) $ \\poly -> do\n  --   -- let Just (fr, to) = Core.anglespan (thescene^.player.position) poly\n  --   --\n  --   -- Cairo.setSourceRGBA 0.28 0.71 0.84 1.00\n  --   -- Cairo.setLineWidth 2\n  --   --\n  --   -- vectorise Cairo.moveTo (thescene^.player.position)\n  --   -- vectorise Cairo.lineTo $ snd fr\n  --   -- Cairo.stroke\n  --   --\n  --   -- vectorise Cairo.moveTo (thescene^.player.position)\n  --   -- vectorise Cairo.lineTo $ snd to\n  --   -- Cairo.stroke\n\n  -- Render shadows\n  shadows thescene\n\n  -- Render vertex markers\n  -- forM (thescene^.obstacles) cornerMarkers\n\n  -- NPCs\n  forM (thescene^.npcs) $ \\n -> do\n    vectorise Cairo.arc (n^.position) 12.0 0 (2*\u03c0)\n    choose (n^.colour)\n    Cairo.fill\n\n  --\n  forM (map (+(200:+150)) [20:+20, 300:+32, 200:+10, 20:+20]) $ \\p -> vectorise Cairo.arc p 8 0 (2*\u03c0) >> Cairo.setSourceRGBA 0.2 0.4 0.6 1.0 >> Cairo.fill\n\n  -- Render player\n  character (thescene^.player)\n  return ()\n\n\n-- |\ncornerMarkers :: Polygon Double -> Cairo.Render ()\ncornerMarkers poly = do\n  Cairo.setSourceRGBA 0.94 0.06 0.05 1.00\n  Cairo.setFontSize 16\n  forM (zip [0..] poly) $ \\(i, p) -> do\n    vectorise Cairo.moveTo p\n    Cairo.showText $ show i\n  return ()\n\n\n-- |\nbackground :: AppState -> Cairo.Render ()\nbackground appstate = perhaps pass (M.lookup \"tree\" (appstate^.assets.images)) $ \\im -> Render.image (600:+5) im\n\n\n-- |\nshadows :: Scene -> Cairo.Render ()\nshadows thescene = do\n  forM (thescene^.obstacles) $ \\poly -> do\n    shadow (thescene^.player) poly\n  return ()\n\n\n-- |\nshadow :: Character -> Polygon Double -> Cairo.Render ()\nshadow char poly = do\n  let Just (fr, to) = Core.anglespan pos poly\n      pos@(px:+py)  = char^.position\n      [\u03b1, \u03b2] = map (snd . polar . subtract (px:+py) . snd) [fr, to]\n\n  -- Cairo.resetClip\n  -- Cairo.setFillRule Cairo.FillRuleEvenOdd\n\n  -- Clip to shadow triangle\n  -- vectorise Cairo.moveTo pos\n  -- vectorise Cairo.lineTo $ pos + mkPolar 800 \u03b1\n  -- vectorise Cairo.lineTo $ pos + mkPolar 800 \u03b2\n  -- Cairo.clip\n  -- Cairo.resetClip\n\n  -- Another clip (overlapping) encompassing the polygon and the non-occluded portion of the ground\n  -- polygon $ [pos, snd $ fr] ++ (take (fst fr - fst to) . drop (fst to) $ cycle poly)\n  maybe pass Render.linepath (Core.distantEdge pos poly)\n  -- Cairo.liftIO $ print $ (uncurry ((,) `on` fst)) <$> Core.anglespan pos poly\n  -- Cairo.setSourceRGBA 0.91 0.02 0.40 1.00\n  -- Cairo.setLineWidth 8\n  -- Cairo.stroke\n\n  -- vectorise Cairo.moveTo $ pos\n  vectorise Cairo.lineTo $ pos + mkPolar 1200 \u03b1\n  arc 1200 (min \u03b1 \u03b2) (max \u03b1 \u03b2) pos\n  vectorise Cairo.lineTo $ pos + mkPolar 1200 \u03b2\n  -- Cairo.closePath\n  -- vectorise Cairo.lineTo $ pos + mkPolar 1200 \u03b1\n  -- arc 1200 (min \u03b1 \u03b2) (max \u03b1 \u03b2) pos\n  -- arcDebug 1200 (min \u03b1 \u03b2) (max \u03b1 \u03b2) pos\n  -- Cairo.setSourceRGBA 0.31 0.31 0.31 0.47\n  -- Cairo.fill\n  -- Cairo.clip\n\n  when True $ Cairo.withRadialPattern px py 40 px py 1200 $ \\pattern -> do\n    Cairo.patternAddColorStopRGBA pattern 0.0 1.0 1.0 1.0 0.9\n    Cairo.patternAddColorStopRGBA pattern 1.0 0.0 0.0 0.0 0.9\n    Cairo.setSource pattern\n    Cairo.fill\n\n  Cairo.resetClip\n\n\n-- |\narcDebug :: Double -> Double -> Double -> Complex Double -> Cairo.Render ()\narcDebug r \u03b1 \u03b2 centre = do\n  arc r \u03b1 \u03b2 centre\n  Cairo.setSourceRGBA 0.12 0.53 0.5 0.53\n  Cairo.fill\n\n  Cairo.setLineWidth 8\n  arc r \u03b1 \u03b2 centre\n  Cairo.stroke\n\n  Cairo.setLineWidth 3\n  arc (r*0.06) \u03b1 \u03b2 centre\n  Cairo.stroke\n\n  Cairo.setLineWidth 4\n  arc (r*0.12) 0.0 \u03b1 centre\n  Cairo.setSourceRGBA 0.7 0.02 0.78 0.74\n  Cairo.stroke\n\n  Cairo.setLineWidth 4\n  arc (r*0.18) 0.0 \u03b2 centre\n  Cairo.setSourceRGBA 0.08 0.42 0.15 0.51\n  Cairo.stroke\n\n-- |\narc :: Double -> Double -> Double -> Complex Double -> Cairo.Render ()\narc r \u03b1 \u03b2 (cx:+cy) = Cairo.arc cx cy r \u03b1 \u03b2\n\n\n-- |\ncircle :: Double -> Complex Double -> Cairo.Render ()\ncircle r centre = arc r 0 \u03c0 centre\n\n\n-- |\npolygon :: Polygon Double -> Cairo.Render ()\npolygon (p:oints) = vectorise Cairo.moveTo p >> mapM (vectorise Cairo.lineTo) oints >> Cairo.closePath\n\n\n-- |\npolygonDebug :: Complex Double -> Polygon Double -> Cairo.Render ()\npolygonDebug pos poly = do\n  polygon poly >> Cairo.setSourceRGBA 0.38 0.84 0.09 0.67 >> Cairo.fill\n  Cairo.setSourceRGBA 0.24 0.16 0.40 1.00\n  Cairo.setFontSize 14\n  forM (zip [(0 :: Int)..] poly) $ \\(i, p) -> do\n    vectorise Cairo.moveTo p\n    Cairo.showText $ (printf \"%d (%.02f\u00b0)\" i (todeg . Core.normalise $ Core.angle pos p :: Double) :: String)\n  pass\n\n\n-- |\ncharacter :: Character -> Cairo.Render ()\ncharacter char = do\n  vectorise Cairo.arc p 12.0 0 (2*\u03c0)\n  choose (char^.colour)\n  Cairo.fill\n\n  Render.linepath [char^.position, char^.position + (800:+0)]\n  Cairo.setSourceRGBA 1.00 0.00 0.00 1.00\n  Cairo.setLineWidth  2.0\n  Cairo.stroke\n\n  Render.linepath [char^.position, char^.position + (0:+800)]\n  Cairo.setSourceRGBA 0.00 0.00 1.00 1.00\n  Cairo.setLineWidth  2.0\n  Cairo.stroke\n\n  choose Palette.mediumslateblue\n  Cairo.setFontSize 16\n  Render.anchoredText (p + (12:+(-12))) (0.0:+1.0) Cairo.showText (char^.name)\n  where\n    p = char^.position\n    choose (r, g, b, a) = Cairo.setSourceRGBA r g b a\n", "meta": {"hexsha": "913b54b32e19527d04c160e52f12f80b31e3de6a", "size": 7607, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Occlusion/Render.hs", "max_stars_repo_name": "SwiftsNamesake/Occlusion", "max_stars_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Occlusion/Render.hs", "max_issues_repo_name": "SwiftsNamesake/Occlusion", "max_issues_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Occlusion/Render.hs", "max_forks_repo_name": "SwiftsNamesake/Occlusion", "max_forks_repo_head_hexsha": "9407b16627ad46e0c226f7b305d2e5bf34c41da7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.831372549, "max_line_length": 154, "alphanum_fraction": 0.5613250953, "num_tokens": 2095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.36296919862864757, "lm_q1q2_score": 0.1970426508580408}}
{"text": "{-# LANGUAGE RecordWildCards, ScopedTypeVariables #-}\nmodule Data.Eigen.Matrix.Mutable (\n    MMatrix(..),\n    MMatrixXf,\n    MMatrixXd,\n    MMatrixXcf,\n    MMatrixXcd,\n    IOMatrix,\n    STMatrix,\n    -- * Construction\n    new,\n    replicate,\n    -- * Consistency check\n    valid,\n    -- * Accessing individual elements\n    read,\n    write,\n    unsafeRead,\n    unsafeWrite,\n    -- * Modifying matrices\n    set,\n    copy,\n    unsafeCopy,\n    -- * Raw pointers\n    unsafeWith\n) where\n\nimport Prelude hiding (read, replicate)\nimport Control.Monad.Primitive\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Data.Complex\nimport Text.Printf\nimport qualified Data.Vector.Storable.Mutable as VSM\nimport qualified Data.Eigen.Internal as I\n\n-- | Mutable matrix. You can modify elements\ndata MMatrix a b s = MMatrix {\n    mm_rows :: Int,\n    mm_cols :: Int,\n    mm_vals :: VSM.MVector s b\n}\n\n-- | Alias for single precision mutable matrix\ntype MMatrixXf = MMatrix Float CFloat\n-- | Alias for double precision mutable matrix\ntype MMatrixXd = MMatrix Double CDouble\n-- | Alias for single previsiom mutable matrix of complex numbers\ntype MMatrixXcf = MMatrix (Complex Float) (I.CComplex CFloat)\n-- | Alias for double prevision mutable matrix of complex numbers\ntype MMatrixXcd = MMatrix (Complex Double) (I.CComplex CDouble)\n\ntype IOMatrix a b = MMatrix a b RealWorld\ntype STMatrix a b s = MMatrix a b s\n\n-- | Verify matrix dimensions and memory layout\nvalid :: I.Elem a b => MMatrix a b s -> Bool\nvalid MMatrix{..} = mm_rows >= 0 && mm_cols >= 0 && VSM.length mm_vals == mm_rows * mm_cols\n\n-- | Create a mutable matrix of the given size and fill it with 0 as an initial value.\nnew :: (PrimMonad m, I.Elem a b) => Int -> Int -> m (MMatrix a b (PrimState m))\nnew rows cols = replicate rows cols 0\n\n-- | Create a mutable matrix of the given size and fill it with as an initial value.\nreplicate :: (PrimMonad m, I.Elem a b) => Int -> Int -> a -> m (MMatrix a b (PrimState m))\nreplicate rows cols val = do\n    vals <- VSM.replicate (rows * cols) (I.cast val)\n    return $ MMatrix rows cols vals\n\n-- | Set all elements of the matrix to the given value\nset :: (PrimMonad m, I.Elem a b) => (MMatrix a b (PrimState m)) -> a -> m ()\nset MMatrix{..} val = VSM.set mm_vals (I.cast val)\n\n-- | Copy a matrix. The two matrices must have the same size and may not overlap.\ncopy :: (PrimMonad m, I.Elem a b) => (MMatrix a b (PrimState m)) -> (MMatrix a b (PrimState m)) -> m ()\ncopy m1 m2\n    | not (valid m1) = fail \"MMatrix.copy: lhs matrix layout is invalid\"\n    | not (valid m2) = fail \"MMatrix.copy: rhs matrix layout is invalid\"\n    | mm_rows m1 /= mm_rows m2 = fail \"MMatrix.copy: matrices have different number of cols\"\n    | mm_cols m1 /= mm_cols m2 = fail \"MMatrix.copy: matrices have different number of rows\"\n    | otherwise = VSM.copy (mm_vals m1) (mm_vals m2)\n\n-- | Yield the element at the given position.\nread :: (PrimMonad m, I.Elem a b) => MMatrix a b (PrimState m) -> Int -> Int -> m a\nread mm@MMatrix{..} row col\n    | not (valid mm) = fail \"MMatrix.read: matrix layout is invalid\"\n    | row < 0 || row >= mm_rows = fail $ printf \"MMatrix.read: row %d is out of bounds [0..%d)\" row mm_rows\n    | col < 0 || col >= mm_cols = fail $ printf \"MMatrix.read: col %d is out of bounds [0..%d)\" col mm_cols\n    | otherwise = unsafeRead mm row col\n\n-- | Replace the element at the given position.\nwrite :: (PrimMonad m, I.Elem a b) => MMatrix a b (PrimState m) -> Int -> Int -> a -> m ()\nwrite mm@MMatrix{..} row col val\n    | not (valid mm) = fail \"MMatrix.write: matrix layout is invalid\"\n    | row < 0 || row >= mm_rows = fail $ printf \"MMatrix.write: row %d is out of bounds [0..%d)\" row mm_rows\n    | col < 0 || col >= mm_cols = fail $ printf \"MMatrix.write: col %d is out of bounds [0..%d)\" col mm_cols\n    | otherwise = unsafeWrite mm row col val\n\n-- | Copy a matrix. The two matrices must have the same size and may not overlap however no bounds check performaned to it may SEGFAULT for incorrect input.\nunsafeCopy :: (PrimMonad m, I.Elem a b) => (MMatrix a b (PrimState m)) -> (MMatrix a b (PrimState m)) -> m ()\nunsafeCopy m1 m2 = VSM.unsafeCopy (mm_vals m1) (mm_vals m2)\n\n-- | Yield the element at the given position. No bounds checks are performed.\nunsafeRead :: (PrimMonad m, I.Elem a b) => MMatrix a b (PrimState m) -> Int -> Int -> m a\nunsafeRead MMatrix{..} row col = VSM.unsafeRead mm_vals (col * mm_rows + row) >>= \\val -> return (I.cast val)\n\n-- | Replace the element at the given position. No bounds checks are performed.\nunsafeWrite :: (PrimMonad m, I.Elem a b) => MMatrix a b (PrimState m) -> Int -> Int -> a -> m ()\nunsafeWrite MMatrix{..} row col val = VSM.unsafeWrite mm_vals (col * mm_rows + row) (I.cast val)\n\n-- | Pass a pointer to the matrix's data to the IO action. Modifying data through the pointer is unsafe if the matrix could have been frozen before the modification.\nunsafeWith :: I.Elem a b => IOMatrix a b -> (Ptr b -> CInt -> CInt -> IO c) -> IO c\nunsafeWith mm@MMatrix{..} f\n    | not (valid mm) = fail \"mutable matrix layout is invalid\"\n    | otherwise = VSM.unsafeWith mm_vals $ \\p -> f p (I.cast mm_rows) (I.cast mm_cols)\n\n", "meta": {"hexsha": "d939bca3fde27f054fd968b2d8d77400a7783d80", "size": 5145, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Data/Eigen/Matrix/Mutable.hs", "max_stars_repo_name": "osidorkin/haskell-eigen", "max_stars_repo_head_hexsha": "2537faa99d3714d6a4c7621433f854e46f07f296", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25, "max_stars_repo_stars_event_min_datetime": "2015-04-06T06:36:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T08:19:06.000Z", "max_issues_repo_path": "Data/Eigen/Matrix/Mutable.hs", "max_issues_repo_name": "osidorkin/haskell-eigen", "max_issues_repo_head_hexsha": "2537faa99d3714d6a4c7621433f854e46f07f296", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15, "max_issues_repo_issues_event_min_datetime": "2015-04-06T06:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-21T18:13:08.000Z", "max_forks_repo_path": "Data/Eigen/Matrix/Mutable.hs", "max_forks_repo_name": "osidorkin/haskell-eigen", "max_forks_repo_head_hexsha": "2537faa99d3714d6a4c7621433f854e46f07f296", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2015-03-29T07:08:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-09T03:08:23.000Z", "avg_line_length": 43.9743589744, "max_line_length": 165, "alphanum_fraction": 0.6732750243, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.1961615881536702}}
{"text": "{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE TypeApplications #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE UndecidableInstances #-}\n\nmodule LatticeSymmetries.Sparse where\n\n-- import Data.Binary (Binary (..))\n\n-- import Data.Vector.Binary\n\n-- import Control.Exception.Safe (bracket, impureThrow, throwIO)\nimport Control.Monad.Primitive (PrimMonad, PrimState)\nimport Control.Monad.ST\n-- import qualified Control.Monad.ST.Unsafe (unsafeIOToST)\n-- import Data.Aeson\n-- import Data.Aeson.Types (typeMismatch)\n\n-- import Data.Scientific (toRealFloat)\n\nimport Data.Bits (Bits, toIntegralSized)\nimport Data.Complex\nimport Data.Type.Equality\n-- import qualified Data.List\n-- import qualified Data.List.NonEmpty as NonEmpty\n\n-- import qualified Data.Vector.Fusion.Stream.Monadic as Stream\n\n-- import qualified Data.Vector.Storable as S\nimport qualified Data.Vector\nimport qualified Data.Vector as B\nimport qualified Data.Vector.Algorithms.Intro as Intro\nimport Data.Vector.Fusion.Bundle (Bundle)\nimport qualified Data.Vector.Fusion.Bundle as Bundle (inplace)\nimport qualified Data.Vector.Fusion.Bundle.Monadic as Bundle\nimport Data.Vector.Fusion.Bundle.Size (Size (..), toMax)\nimport Data.Vector.Fusion.Stream.Monadic (Step (..), Stream (..))\nimport qualified Data.Vector.Fusion.Util (unId)\nimport Data.Vector.Generic ((!))\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as GM\nimport qualified Data.Vector.Storable\nimport qualified Data.Vector.Unboxed\n-- import qualified Data.Vector.Storable.Mutable as SM\n-- import Data.Vector.Unboxed (Unbox)\n-- import qualified Data.Vector.Unboxed as U\n-- import Data.Yaml (decodeFileWithWarnings)\n-- import Foreign.C.String (CString, peekCString)\n-- import Foreign.C.Types (CInt (..), CUInt (..))\n-- import Foreign.ForeignPtr\n-- import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)\n-- import Foreign.Marshal.Alloc (alloca, free, malloc, mallocBytes)\n-- import Foreign.Marshal.Array (newArray, withArrayLen)\n-- import Foreign.Marshal.Utils (new, with)\n-- import Foreign.Ptr (FunPtr, Ptr, castPtr)\n-- import Foreign.StablePtr\n-- import Foreign.Storable (Storable (..))\nimport qualified GHC.Exts as GHC (IsList (..))\nimport GHC.TypeLits\nimport qualified GHC.TypeLits as GHC\nimport qualified Unsafe.Coerce\n-- import qualified GHC.ForeignPtr as GHC (Finalizers (..), ForeignPtr (..), ForeignPtrContents (..))\n-- import GHC.Generics\n-- import qualified GHC.IORef as GHC (atomicSwapIORef)\n-- import GHC.Prim\n-- import qualified GHC.Ptr as GHC (Ptr (..))\n-- import qualified Language.C.Inline as C\n-- import qualified Language.C.Inline.Unsafe as CU\n-- import LatticeSymmetries.Context\n-- import LatticeSymmetries.IO\n-- import LatticeSymmetries.Types\n-- import qualified System.IO.Unsafe\n-- import qualified System.Mem.Weak\nimport Prelude hiding (group, product, sort)\n\n-- C.context (C.baseCtx <> C.bsCtx <> C.funCtx <> lsCtx)\n-- C.include \"<lattice_symmetries/lattice_symmetries.h>\"\n-- C.include \"helpers.h\"\n\ntype KnownDenseMatrix v r c a = (G.Vector v a, KnownNat r, KnownNat c)\n\ntype KnownCOO v i r c a = (G.Vector v (i, i, a), KnownNat r, KnownNat c)\n\ntype KnownCSR v i r c a = (G.Vector v i, G.Vector v a, KnownNat r, KnownNat c)\n\nnatToInt :: forall n. KnownNat n => Int\nnatToInt = fromIntegral $ GHC.TypeLits.natVal (Proxy @n)\n\n-- | Dense matrix in row-major order (C layout)\ndata DenseMatrix v (r :: Nat) (c :: Nat) a = DenseMatrix {dmData :: !(v a)}\n  deriving stock (Show, Eq, Generic)\n\ntype StorableDenseMatrix r c a = DenseMatrix Data.Vector.Storable.Vector r c a\n\ntype UnboxedDenseMatrix r c a = DenseMatrix Data.Vector.Unboxed.Vector r c a\n\ntype BoxedDenseMatrix r c a = DenseMatrix Data.Vector.Vector r c a\n\n-- | Get number of rows in the matrix\ndmRows :: forall r c a v. KnownDenseMatrix v r c a => DenseMatrix v r c a -> Int\ndmRows _ = natToInt @r\n{-# INLINE dmRows #-}\n\n-- | Get number of columns in the matrix\ndmCols :: forall r c a v. KnownDenseMatrix v r c a => DenseMatrix v r c a -> Int\ndmCols _ = natToInt @c\n{-# INLINE dmCols #-}\n\n-- | Get matrix shape\ndmShape :: forall r c a v. KnownDenseMatrix v r c a => DenseMatrix v r c a -> (Int, Int)\ndmShape m = (dmRows m, dmCols m)\n{-# INLINE dmShape #-}\n\ninstance (KnownDenseMatrix v r c a, Num a) => Num (DenseMatrix v r c a) where\n  (+) a b = DenseMatrix $ G.zipWith (+) (dmData a) (dmData b)\n  (-) a b = DenseMatrix $ G.zipWith (-) (dmData a) (dmData b)\n  (*) a b = DenseMatrix $ G.zipWith (*) (dmData a) (dmData b)\n  abs a = DenseMatrix $ G.map abs (dmData a)\n  signum _ = error \"Num instance for DenseMatrix does not implement signum\"\n  fromInteger z = DenseMatrix $ G.replicate (natToInt @r * natToInt @c) (fromInteger z)\n\n-- | Sparse matrix in Coordinate format\ndata COO v i (r :: Nat) (c :: Nat) a = COO {cooData :: !(v (i, i, a))}\n  deriving stock (Generic)\n\nderiving instance Show (v (i, i, a)) => Show (COO v i r c a)\n\nderiving instance Eq (v (i, i, a)) => Eq (COO v i r c a)\n\n-- | Get number of rows in the matrix\ncooRows :: forall r c a i v. KnownCOO v i r c a => COO v i r c a -> Int\ncooRows _ = natToInt @r\n{-# INLINE cooRows #-}\n\n-- | Get number of columns in the matrix\ncooCols :: forall r c a i v. KnownCOO v i r c a => COO v i r c a -> Int\ncooCols _ = natToInt @c\n{-# INLINE cooCols #-}\n\n-- | Get matrix shape\ncooShape :: forall r c a i v. KnownCOO v i r c a => COO v i r c a -> (Int, Int)\ncooShape m = (cooRows m, cooCols m)\n{-# INLINE cooShape #-}\n\ndata CSR v i (r :: Nat) (c :: Nat) a = CSR\n  { csrOffsets :: !(v i),\n    csrIndices :: !(v i),\n    csrData :: !(v a)\n  }\n  deriving stock (Generic)\n\nderiving instance (Show (v i), Show (v a)) => Show (CSR v i r c a)\n\nderiving instance (Eq (v i), Eq (v a)) => Eq (CSR v i r c a)\n\ndata SomeCSR v i a where\n  SomeCSR :: (KnownNat r, KnownNat c) => CSR v i r c a -> SomeCSR v i a\n\nsameShape ::\n  forall r\u2081 c\u2081 r\u2082 c\u2082 a\u2081 a\u2082 v\u2081 v\u2082 i\u2081 i\u2082.\n  (KnownCSR v\u2081 i\u2081 r\u2081 c\u2081 a\u2081, KnownCSR v\u2082 i\u2082 r\u2082 c\u2082 a\u2082) =>\n  CSR v\u2081 i\u2081 r\u2081 c\u2081 a\u2081 ->\n  CSR v\u2082 i\u2082 r\u2082 c\u2082 a\u2082 ->\n  Maybe ('(r\u2081, c\u2081) :~: '(r\u2082, c\u2082))\nsameShape a b =\n  case sameNat (Proxy @r\u2081) (Proxy @r\u2082) of\n    Just Refl -> case sameNat (Proxy @c\u2081) (Proxy @c\u2082) of\n      Just Refl -> Just Refl\n      Nothing -> Nothing\n    Nothing -> Nothing\n\nwithSomeCsr ::\n  (G.Vector v i, G.Vector v a) =>\n  SomeCSR v i a ->\n  (forall r c. (KnownNat r, KnownNat c) => CSR v i r c a -> b) ->\n  b\nwithSomeCsr (SomeCSR m) f = f m\n{-# INLINE withSomeCsr #-}\n\n-- | Binary search in a vector. Return index, if found.\nbinarySearch :: (G.Vector v a, Ord a) => v a -> a -> Maybe Int\nbinarySearch v z = go 0 (G.length v)\n  where\n    {-# INLINE go #-}\n    go !l !u\n      | l < u =\n        -- NOTE: we assume that the vector is short enought such that @u + l@ does not overflow\n        let !m = (u + l) `div` 2\n         in case compare (v ! m) z of\n              LT -> go (m + 1) u\n              EQ -> Just m\n              GT -> go l m\n      | otherwise = Nothing\n{-# INLINE binarySearch #-}\n\ncsrIndex :: (KnownCSR v i r c a, Integral i, Num a) => CSR v i r c a -> (Int, Int) -> a\ncsrIndex matrix (i, j) =\n  case binarySearch (G.slice l (u - l) (csrIndices matrix)) (fromIntegral j) of\n    Just k -> csrData matrix ! (l + k)\n    Nothing -> 0\n  where\n    !l = fromIntegral $ csrOffsets matrix ! i\n    !u = fromIntegral $ csrOffsets matrix ! (i + 1)\n{-# INLINE csrIndex #-}\n\ncsrNumberNonZero :: KnownCSR v i r c a => CSR v i r c a -> Int\ncsrNumberNonZero = G.length . csrIndices\n{-# INLINE csrNumberNonZero #-}\n\ncsrRows :: forall r c a i v. KnownNat r => CSR v i r c a -> Int\ncsrRows _ = natToInt @r\n{-# INLINE csrRows #-}\n\ncsrCols :: forall r c a i v. KnownNat c => CSR v i r c a -> Int\ncsrCols _ = natToInt @c\n{-# INLINE csrCols #-}\n\ncsrShape :: (KnownNat r, KnownNat c) => CSR v i r c a -> (Int, Int)\ncsrShape csr = (csrRows csr, csrCols csr)\n{-# INLINE csrShape #-}\n\ncsrTraverseIndex ::\n  forall i\u2081 i\u2082 f v r c a.\n  (Applicative f, KnownCSR v i\u2081 r c a, KnownCSR v i\u2082 r c a) =>\n  (i\u2081 -> f i\u2082) ->\n  CSR v i\u2081 r c a ->\n  f (CSR v i\u2082 r c a)\ncsrTraverseIndex f (CSR offsets indices elements) = construct <$> offsets' <*> indices'\n  where\n    construct o i = CSR o i elements\n    offsets' = G.fromListN n <$> traverse f (G.toList offsets)\n    indices' = G.fromListN n <$> traverse f (G.toList indices)\n    !n = G.length indices\n{-# INLINE csrTraverseIndex #-}\n\n-- | Change the underlying integral type. Returns a @Maybe@ because casts may overflow.\ncsrReIndex ::\n  (KnownCSR v i\u2081 r c a, KnownCSR v i\u2082 r c a, Bits i\u2081, Integral i\u2081, Bits i\u2082, Integral i\u2082) =>\n  CSR v i\u2081 r c a ->\n  Maybe (CSR v i\u2082 r c a)\ncsrReIndex = csrTraverseIndex toIntegralSized\n{-# INLINE csrReIndex #-}\n\n-- | Change the underlying vector type.\ncsrReVector ::\n  (KnownCSR v\u2081 i r c a, KnownCSR v\u2082 i r c a) =>\n  CSR v\u2081 i r c a ->\n  CSR v\u2082 i r c a\ncsrReVector (CSR offsets indices elements) =\n  CSR (G.convert offsets) (G.convert indices) (G.convert elements)\n{-# INLINE csrReVector #-}\n\ncooToBundle :: KnownCOO v i r c a => COO v i r c a -> Bundle v (i, i, a)\ncooToBundle = G.stream . cooData\n\ncooFromBundle :: KnownCOO v i r c a => Bundle v (i, i, a) -> COO v i r c a\ncooFromBundle = COO . G.unstream . Bundle.reVector\n\ncomputeShape :: (Integral i, G.Vector v (i, i, a)) => v (i, i, a) -> (Int, Int)\ncomputeShape v\n  | G.null v = (0, 0)\n  | otherwise = (fromIntegral maxRow + 1, fromIntegral maxColumn + 1)\n  where\n    (maxRow, maxColumn) = G.foldl' combine (0, 0) v\n    combine (!r, !c) (!i, !j, _) = let !r' = max i r; !c' = max j c in (r', c')\n\ndata CombineNeighborsHelper a\n  = CombineNeighborsFirst\n  | CombineNeighborsPrevious !a\n  | CombineNeighborsDone\n\ncombineNeighborsImpl :: Monad m => (a -> a -> Bool) -> (a -> a -> a) -> Stream m a -> Stream m a\n{-# INLINE combineNeighborsImpl #-}\ncombineNeighborsImpl equal combine (Stream step s\u2080) = Stream step' (CombineNeighborsFirst, s\u2080)\n  where\n    {-# INLINE step' #-}\n    step' (CombineNeighborsFirst, s) = do\n      r <- step s\n      case r of\n        Yield a s' -> pure $ Skip (CombineNeighborsPrevious a, s')\n        Skip s' -> pure $ Skip (CombineNeighborsFirst, s')\n        Done -> pure $ Done\n    step' (CombineNeighborsPrevious a, s) = do\n      r <- step s\n      case r of\n        Yield b s' ->\n          if equal a b\n            then pure $ Skip (CombineNeighborsPrevious (combine a b), s')\n            else pure $ Yield a (CombineNeighborsPrevious b, s')\n        Skip s' -> pure $ Skip (CombineNeighborsPrevious a, s')\n        Done -> pure $ Yield a (CombineNeighborsDone, s)\n    step' (CombineNeighborsDone, _) = pure $ Done\n\ncombineNeighbors :: G.Vector v a => (a -> a -> Bool) -> (a -> a -> a) -> v a -> v a\ncombineNeighbors equal combine =\n  G.unstream . Bundle.inplace (combineNeighborsImpl equal combine) toMax . G.stream\n\ncooNormalize :: (KnownCOO v i r c a, Integral i, Num a) => COO v i r c a -> COO v i r c a\ncooNormalize (COO v) = COO v'\n  where\n    comparison (i\u2081, j\u2081, _) (i\u2082, j\u2082, _) = compare (i\u2081, j\u2081) (i\u2082, j\u2082)\n    group =\n      combineNeighbors\n        (\\(i\u2081, j\u2081, _) (i\u2082, j\u2082, _) -> i\u2081 == i\u2082 && j\u2081 == j\u2082)\n        (\\(i, j, a) (_, _, b) -> (i, j, a + b))\n    sort x = runST $ do\n      buffer <- G.thaw x\n      Intro.sortBy comparison buffer\n      G.unsafeFreeze buffer\n    v' = group $ sort v\n\n-- preprocessCoo :: Num a => [(Int, Int, a)] -> [(Int, Int, a)]\n-- preprocessCoo =\n--   fmap (Data.List.foldl1' (\\(!i, !j, !x) (_, _, y) -> (i, j, x + y)))\n--     . Data.List.groupBy (\\a b -> key a == key b)\n--     . sortOn key\n--   where\n--     key (i, j, _) = (i, j)\n\nunsafeCooToCsr ::\n  (KnownCOO v1 i r c a, KnownCSR v2 i r c a, G.Vector v1 a, G.Vector v1 i, Integral i) =>\n  COO v1 i r c a ->\n  CSR v2 i r c a\nunsafeCooToCsr coo@(COO coordinates) = CSR offsets indices elements\n  where\n    indices = G.convert $ G.map (\\(_, j, _) -> j) coordinates\n    elements = G.convert $ G.map (\\(_, _, x) -> x) coordinates\n    n = cooRows coo\n    offsets = runST $ do\n      rs <- GM.replicate (n + 1) 0\n      G.forM_ coordinates $ \\(!i, _, _) ->\n        GM.modify rs (+ 1) (fromIntegral i + 1)\n      loopM 0 (< n) (+ 1) $ \\ !i -> do\n        r <- GM.read rs i\n        GM.modify rs (+ r) (i + 1)\n      G.unsafeFreeze rs\n\ncooToCsr ::\n  forall v1 v2 i r c a.\n  (KnownCOO v1 i r c a, KnownCSR v2 i r c a, G.Vector v1 a, G.Vector v1 i, Integral i, Num a) =>\n  COO v1 i r c a ->\n  CSR v2 i r c a\ncooToCsr = unsafeCooToCsr . cooNormalize\n\ncsrOffsetsToIndices :: (G.Vector v i, Integral i) => v i -> v i\ncsrOffsetsToIndices offsets = runST $ do\n  let nRows = G.length offsets - 1\n      nnz = fromIntegral $ G.last offsets\n  indices <- GM.new nnz\n  loopM 0 (< nRows) (+ 1) $ \\i ->\n    let !b = fromIntegral $ offsets ! i\n        !e = fromIntegral $ offsets ! (i + 1)\n     in GM.set (GM.slice b (e - b) indices) (fromIntegral i)\n  G.unsafeFreeze indices\n\ncsrToCoo ::\n  forall v1 v2 i r c a.\n  (KnownCSR v1 i r c a, KnownCOO v2 i r c a, G.Vector v2 a, G.Vector v2 i, Integral i) =>\n  CSR v1 i r c a ->\n  COO v2 i r c a\ncsrToCoo csr = COO v\n  where\n    v =\n      G.zip3\n        (G.convert $ csrOffsetsToIndices (csrOffsets csr))\n        (G.convert $ csrIndices csr)\n        (G.convert $ csrData csr)\n\ndenseToCoo ::\n  forall v1 v2 i r c a.\n  (KnownDenseMatrix v1 r c a, KnownCOO v2 i r c a, Eq a, Num a, Integral i) =>\n  DenseMatrix v1 r c a ->\n  COO v2 i r c a\ndenseToCoo dense = COO v\n  where\n    numberRows = dmRows dense\n    numberCols = dmCols dense\n    v =\n      G.unstream\n        . Bundle.filter (\\(_, _, x) -> x /= 0)\n        . Bundle.map (\\(i, j) -> (fromIntegral i, fromIntegral j, indexDenseMatrix dense i j))\n        $ cartesian\n          (Bundle.enumFromStepN 0 1 numberRows)\n          (Bundle.enumFromStepN 0 1 numberCols)\n\ndenseToCsr ::\n  forall v i r c a.\n  (KnownDenseMatrix v r c a, KnownCSR v i r c a, Eq a, Num a, Integral i) =>\n  DenseMatrix v r c a ->\n  CSR v i r c a\ndenseToCsr = cooToCsr . denseToCoo @v @Data.Vector.Vector\n\ncooToDense ::\n  forall v1 v2 i r c a.\n  (HasCallStack, KnownCOO v1 i r c a, KnownDenseMatrix v2 r c a, Integral i) =>\n  COO v1 i r c a ->\n  DenseMatrix v2 r c a\ncooToDense coo\n  | (n, m) == (natToInt @r, natToInt @c) = runST $ do\n    elements <- GM.new (n * m)\n    G.forM_ (cooData coo) $ \\(i, j, x) ->\n      GM.write elements (fromIntegral i * m + fromIntegral j) x\n    DenseMatrix <$> G.unsafeFreeze elements\n  | otherwise = error \"incompatible shape\"\n  where\n    (n, m) = cooShape coo\n\ncsrToDense ::\n  forall v i r c a.\n  (KnownDenseMatrix v r c a, KnownCSR v i r c a, G.Vector v (i, i, a), Integral i) =>\n  CSR v i r c a ->\n  DenseMatrix v r c a\ncsrToDense = cooToDense . csrToCoo @v @Data.Vector.Vector\n\n-- csrFromList :: KnownCSR v i r c a => [(i, i, a)] -> CSR v i r c a\n-- csrFromList = undefined\n\nsomeCsrShape :: SomeCSR v i a -> (Int, Int)\nsomeCsrShape (SomeCSR m) = csrShape m\n\ncartesian :: Bundle v a -> Bundle v b -> Bundle v (a, b)\ncartesian a b =\n  Bundle.fromStream\n    (cartesianImpl (Bundle.elements a) (Bundle.elements b))\n    (Bundle.sSize a `product` Bundle.sSize b)\n  where\n    product Unknown _ = Unknown\n    product _ Unknown = Unknown\n    product (Exact x) (Exact y) = Exact (x * y)\n    product (Exact x) (Max y) = Max (x * y)\n    product (Max x) (Exact y) = Max (x * y)\n    product (Max x) (Max y) = Max (x * y)\n\ncartesianImpl :: Monad m => Stream m a -> Stream m b -> Stream m (a, b)\ncartesianImpl (Stream step1 s1\u2080) (Stream step2 s2\u2080) = Stream step' (Nothing, s1\u2080, s2\u2080)\n  where\n    step' (Just a, s1, s2) = do\n      r\u2082 <- step2 s2\n      case r\u2082 of\n        Yield b s2' -> pure $ Yield (a, b) (Just a, s1, s2')\n        Skip s2' -> pure $ Skip (Just a, s1, s2')\n        -- NOTE: It's important to pass s2\u2080 here!\n        Done -> pure $ Skip (Nothing, s1, s2\u2080)\n    step' (Nothing, s1, s2) = do\n      r\u2081 <- step1 s1\n      case r\u2081 of\n        Yield a s1' -> pure $ Skip (Just a, s1', s2)\n        Skip s1' -> pure $ Skip (Nothing, s1', s2)\n        Done -> pure $ Done\n\n-- mergeImpl :: Stream m a -> Stream m a -> Stream m a\n-- mergeImpl (Stream step1 s1\u2080) (Stream step2 s2\u2080) = Stream step' (s1\u2080, s2\u2080)\n--   where\n--     step' (s1, s2) = do\n\ncooKron ::\n  (KnownCOO v i r1 c1 a, KnownCOO v i r2 c2 a, Num i, Num a) =>\n  COO v i r1 c1 a ->\n  COO v i r2 c2 a ->\n  COO v i (r1 GHC.* r2) (c1 GHC.* c2) a\ncooKron a b = COO v\n  where\n    combine ((i\u2081, j\u2081, x\u2081), (i\u2082, j\u2082, x\u2082)) =\n      (i\u2081 * fromIntegral n\u2081 + i\u2082, j\u2081 * fromIntegral m\u2081 + j\u2082, x\u2081 * x\u2082)\n    v = G.unstream . Bundle.map combine $ cartesian (cooToBundle a) (cooToBundle b)\n    (n\u2081, m\u2081) = cooShape a\n\n-- cooPlus :: (Integral i, Unbox i, Num a, Unbox a) => COO v i r c a -> COO v i r c a -> COO v i r c a\n-- cooPlus a b = undefined\n\nwithSomeNat :: forall r. HasCallStack => Int -> (forall n. KnownNat n => Proxy n -> r) -> r\nwithSomeNat n f = case GHC.TypeLits.someNatVal (fromIntegral n) of\n  Just (SomeNat (Proxy :: Proxy n)) -> f (Proxy @n)\n  Nothing -> error \"negative natural number\"\n\ncsrKron ::\n  forall v i r1 c1 r2 c2 a.\n  ( KnownCSR v i r1 c1 a,\n    KnownCSR v i r2 c2 a,\n    KnownNat (r1 GHC.* r2),\n    KnownNat (c1 GHC.* c2),\n    Integral i,\n    Num a\n  ) =>\n  CSR v i r1 c1 a ->\n  CSR v i r2 c2 a ->\n  CSR v i (r1 GHC.* r2) (c1 GHC.* c2) a\ncsrKron a b = (cooToCsr @B.Vector) $ cooKron (csrToCoo a) (csrToCoo b)\n\nloopM :: Monad m => i -> (i -> Bool) -> (i -> i) -> (i -> m ()) -> m ()\nloopM i\u2080 cond inc action = go i\u2080\n  where\n    go !i\n      | cond i = do () <- action i; go (inc i)\n      | otherwise = pure ()\n{-# INLINE loopM #-}\n\niFoldM :: Monad m => i -> (i -> Bool) -> (i -> i) -> a -> (a -> i -> m a) -> m a\niFoldM i\u2080 cond inc x\u2080 action = go x\u2080 i\u2080\n  where\n    go !x !i\n      | cond i = do !x' <- action x i; go x' (inc i)\n      | otherwise = pure x\n{-# INLINE iFoldM #-}\n\ninstance (KnownCSR v i r c a, Integral i, Eq a, Num a) => Num (CSR v i r c a) where\n  (+) = csrBinaryOp (+)\n  (-) = csrBinaryOp (-)\n  (*) = csrBinaryOp (*)\n  abs m = m {csrData = G.map abs (csrData m)}\n  signum = error \"Num instance for CSR does not implement signum\"\n  fromInteger = error \"Num instance for CSR does not implement fromInteger\"\n\ncsrBinaryOp ::\n  (KnownCSR v i r c a, KnownCSR v i r c b, Integral i, Eq b, Num a, Num b) =>\n  (a -> a -> b) ->\n  CSR v i r c a ->\n  CSR v i r c a ->\n  CSR v i r c b\ncsrBinaryOp op a b = runST $ do\n  outOffsets <- GM.new (csrRows a + 1)\n  let estimatedNumberNonZero = csrNumberNonZero a + csrNumberNonZero b\n  outIndices <- GM.new estimatedNumberNonZero\n  outData <- GM.new estimatedNumberNonZero\n  let consumeBoth !kA !kB !nnz =\n        let !r = op (csrData a ! kA) (csrData b ! kB)\n         in if r /= 0\n              then do\n                GM.write outIndices nnz (csrIndices a ! kA)\n                GM.write outData nnz r\n                pure (nnz + 1)\n              else pure nnz\n      consumeLeft !kA !nnz =\n        let !r = op (csrData a ! kA) 0\n         in if r /= 0\n              then do\n                GM.write outIndices nnz (csrIndices a ! kA)\n                GM.write outData nnz r\n                pure (nnz + 1)\n              else pure nnz\n      consumeRight !kB !nnz =\n        let !r = op 0 (csrData b ! kB)\n         in if r /= 0\n              then do\n                GM.write outIndices nnz (csrIndices b ! kB)\n                GM.write outData nnz r\n                pure (nnz + 1)\n              else pure nnz\n  GM.write outOffsets 0 0\n  nnz <- iFoldM 0 (< csrRows a) (+ 1) 0 $ \\_nnz i -> do\n    let !beginA = fromIntegral $ csrOffsets a ! i\n        !beginB = fromIntegral $ csrOffsets b ! i\n        !endA = fromIntegral $ csrOffsets a ! (i + 1)\n        !endB = fromIntegral $ csrOffsets b ! (i + 1)\n        loop !kA !kB !nnz\n          | kA < endA && kB < endB =\n            let !jA = csrIndices a ! kA\n                !jB = csrIndices b ! kB\n             in case compare jA jB of\n                  EQ -> consumeBoth kA kB nnz >>= loop (kA + 1) (kB + 1)\n                  LT -> consumeLeft kA nnz >>= loop (kA + 1) kB\n                  GT -> consumeRight kB nnz >>= loop kA (kB + 1)\n          | kA < endA = tailLeft kA nnz\n          | otherwise = tailRight kB nnz\n        tailLeft !kA !nnz\n          | kA < endA = consumeLeft kA nnz >>= tailLeft (kA + 1)\n          | otherwise = pure nnz\n        tailRight !kB !nnz\n          | kB < endB = consumeRight kB nnz >>= tailRight (kB + 1)\n          | otherwise = pure nnz\n    nnz <- loop beginA beginB _nnz\n    GM.write outOffsets (i + 1) (fromIntegral nnz)\n    pure nnz\n  CSR\n    <$> G.unsafeFreeze outOffsets\n    <*> G.unsafeFreeze (GM.slice 0 nnz outIndices)\n    <*> G.unsafeFreeze (GM.slice 0 nnz outData)\n\n-- template <class I, class T, class T2, class binary_op>\n-- void csr_binop_csr_canonical(const I n_row, const I n_col,\n--                              const I Ap[], const I Aj[], const T Ax[],\n--                              const I Bp[], const I Bj[], const T Bx[],\n--                                    I Cp[],       I Cj[],       T2 Cx[],\n--                              const binary_op& op)\n-- {\n--     //Method that works for canonical CSR matrices\n--\n--     Cp[0] = 0;\n--     I nnz = 0;\n--\n--     for(I i = 0; i < n_row; i++){\n--         I A_pos = Ap[i];\n--         I B_pos = Bp[i];\n--         I A_end = Ap[i+1];\n--         I B_end = Bp[i+1];\n--\n--         //while not finished with either row\n--         while(A_pos < A_end && B_pos < B_end){\n--             I A_j = Aj[A_pos];\n--             I B_j = Bj[B_pos];\n--\n--             if(A_j == B_j){\n--                 T result = op(Ax[A_pos],Bx[B_pos]);\n--                 if(result != 0){\n--                     Cj[nnz] = A_j;\n--                     Cx[nnz] = result;\n--                     nnz++;\n--                 }\n--                 A_pos++;\n--                 B_pos++;\n--             } else if (A_j < B_j) {\n--                 T result = op(Ax[A_pos],0);\n--                 if (result != 0){\n--                     Cj[nnz] = A_j;\n--                     Cx[nnz] = result;\n--                     nnz++;\n--                 }\n--                 A_pos++;\n--             } else {\n--                 //B_j < A_j\n--                 T result = op(0,Bx[B_pos]);\n--                 if (result != 0){\n--                     Cj[nnz] = B_j;\n--                     Cx[nnz] = result;\n--                     nnz++;\n--                 }\n--                 B_pos++;\n--             }\n--         }\n--\n--         //tail\n--         while(A_pos < A_end){\n--             T result = op(Ax[A_pos],0);\n--             if (result != 0){\n--                 Cj[nnz] = Aj[A_pos];\n--                 Cx[nnz] = result;\n--                 nnz++;\n--             }\n--             A_pos++;\n--         }\n--         while(B_pos < B_end){\n--             T result = op(0,Bx[B_pos]);\n--             if (result != 0){\n--                 Cj[nnz] = Bj[B_pos];\n--                 Cx[nnz] = result;\n--                 nnz++;\n--             }\n--             B_pos++;\n--         }\n--\n--         Cp[i+1] = nnz;\n--     }\n-- }\n\ndenseDot ::\n  forall r c a v.\n  (KnownDenseMatrix v r c a, Num a) =>\n  DenseMatrix v r c a ->\n  DenseMatrix v r c a ->\n  a\ndenseDot a b = let (DenseMatrix c) = a * b in G.sum c\n\ndenseMatMul ::\n  forall r k c a v.\n  (KnownDenseMatrix v r k a, KnownDenseMatrix v k c a, Num a) =>\n  DenseMatrix v r k a ->\n  DenseMatrix v k c a ->\n  DenseMatrix v r c a\ndenseMatMul a b = runST $ do\n  let !nRows = natToInt @r\n      !nCols = natToInt @c\n  cBuffer <- GM.new (nRows * nCols)\n  loopM 0 (< nRows) (+ 1) $ \\i ->\n    loopM 0 (< nCols) (+ 1) $ \\j -> do\n      !cij <- iFoldM 0 (< natToInt @k) (+ 1) (0 :: a) $ \\ !acc k ->\n        let !aik = indexDenseMatrix a i k\n            !bkj = indexDenseMatrix b k j\n         in pure (acc + aik * bkj)\n      GM.write cBuffer (i * nCols + j) cij\n  DenseMatrix <$> G.unsafeFreeze cBuffer\n\nmaxNumNonZeroAfterMatMul ::\n  forall r k c a i v.\n  (KnownCSR v i r k a, KnownCSR v i k c a, G.Vector v Int, Integral i) =>\n  CSR v i r k a ->\n  CSR v i k c a ->\n  Int\nmaxNumNonZeroAfterMatMul a b = runST $ do\n  let nRows = csrRows a\n      nCols = csrCols b\n  mask <- G.unsafeThaw (G.replicate nCols (-1) :: v Int)\n  iFoldM 0 (< nRows) (+ 1) 0 $ \\nnz i ->\n    let jjBegin = fromIntegral $ csrOffsets a ! i\n        jjEnd = fromIntegral $ csrOffsets a ! (i + 1)\n     in iFoldM jjBegin (< jjEnd) (+ 1) nnz $ \\nnzRow jj ->\n          let j = fromIntegral $ csrIndices a ! jj\n              kkBegin = fromIntegral $ csrOffsets b ! j\n              kkEnd = fromIntegral $ csrOffsets b ! (j + 1)\n           in iFoldM kkBegin (< kkEnd) (+ 1) nnzRow $ \\acc kk -> do\n                let k = fromIntegral $ csrIndices b ! kk\n                m <- GM.read mask k\n                if m /= i\n                  then do GM.write mask k i; pure (acc + 1)\n                  else pure acc\n\nsortManyByKey ::\n  (Ord c, PrimMonad m, G.Vector v a, G.Vector v b) =>\n  (a -> b -> c) ->\n  G.Mutable v (PrimState m) a ->\n  G.Mutable v (PrimState m) b ->\n  m ()\nsortManyByKey key a b = do\n  mbuffer <-\n    (G.unsafeThaw =<<) $\n      Data.Vector.zip\n        <$> (G.convert <$> G.unsafeFreeze a)\n        <*> (G.convert <$> G.unsafeFreeze b)\n  Intro.sortBy (comparing (uncurry key)) mbuffer\n  buffer <- G.unsafeFreeze mbuffer\n  G.copy a $ G.convert (G.map fst buffer)\n  G.copy b $ G.convert (G.map snd buffer)\n\ncsrMatMul ::\n  forall r k c a i v.\n  (KnownCSR v i r k a, KnownCSR v i k c a, G.Vector v Int, Integral i, Num a) =>\n  CSR v i r k a ->\n  CSR v i k c a ->\n  CSR v i r c a\ncsrMatMul a b =\n  -- cooToCsr . csrToCoo $\n  runST $ do\n    let !bufferSize = maxNumNonZeroAfterMatMul a b\n        !nRows = csrRows a\n        !nCols = csrCols b\n    outOffsets <- GM.new (nRows + 1)\n    outIndices <- GM.new bufferSize\n    outData <- GM.new bufferSize\n    next <- G.unsafeThaw (G.replicate nCols (-1) :: v Int)\n    sums <- G.unsafeThaw (G.replicate nCols 0 :: v a)\n    nnz <- iFoldM 0 (< nRows) (+ 1) 0 $ \\ !nnz !i -> do\n      let !jjBegin = fromIntegral $ csrOffsets a ! i\n          !jjEnd = fromIntegral $ csrOffsets a ! (i + 1)\n      (head, length) <- iFoldM jjBegin (< jjEnd) (+ 1) (-2 :: Int, 0 :: Int) $\n        \\(!_head, !_length) !jj ->\n          let !j = fromIntegral $ csrIndices a ! jj\n              !v = csrData a ! jj\n              !kkBegin = fromIntegral $ csrOffsets b ! j\n              !kkEnd = fromIntegral $ csrOffsets b ! (j + 1)\n           in iFoldM kkBegin (< kkEnd) (+ 1) (_head, _length) $ \\(!head, !length) !kk -> do\n                let !k = fromIntegral $ csrIndices b ! kk\n                GM.modify sums (+ v * (csrData b ! kk)) k\n                _next <- GM.read next k\n                if _next == -1\n                  then do GM.write next k head; pure (k, length + 1)\n                  else pure (head, length)\n      (_, nnz') <- iFoldM 0 (< length) (+ 1) (head, nnz) $ \\(!head, !nnz) _ -> do\n        GM.write outIndices nnz (fromIntegral head)\n        GM.write outData nnz =<< GM.read sums head\n        head' <- GM.read next head\n        GM.write next head (-1)\n        GM.write sums head 0\n        pure (head', nnz + 1)\n      GM.write outOffsets (i + 1) (fromIntegral nnz')\n      pure nnz'\n    outOffsets' <- G.unsafeFreeze outOffsets\n    loopM 0 (< nRows) (+ 1) $ \\ !i -> do\n      let !jjBegin = fromIntegral $ outOffsets' ! i\n          !jjEnd = fromIntegral $ outOffsets' ! (i + 1)\n          key !j _ = j\n      sortManyByKey\n        (\\j _ -> j)\n        (GM.slice jjBegin (jjEnd - jjBegin) outIndices)\n        (GM.slice jjBegin (jjEnd - jjBegin) outData)\n    CSR\n      <$> pure outOffsets'\n      <*> G.unsafeFreeze (GM.slice 0 nnz outIndices)\n      <*> G.unsafeFreeze (GM.slice 0 nnz outData)\n\n-- void ls_csr_matrix_from_dense(unsigned const dimension,\n--                               _Complex double const *const dense,\n--                               unsigned *offsets, unsigned *columns,\n--                               _Complex double *off_diag_elements,\n--                               _Complex double *diag_elements) {\n--   offsets[0] = 0;\n--   for (unsigned i = 0; i < dimension; ++i) {\n--     unsigned nonzero_in_row = 0;\n--     for (unsigned j = 0; j < dimension; ++j) {\n--       _Complex double const element = dense[i * dimension + j];\n--       if (i == j) {\n--         diag_elements[i] = element;\n--       } else if (element != 0) {\n--         *columns = j;\n--         *off_diag_elements = element;\n--         ++nonzero_in_row;\n--         ++columns;\n--         ++off_diag_elements;\n--       }\n--     }\n--     offsets[i + 1] = offsets[i] + nonzero_in_row;\n--   }\n-- }\n\ndenseEye :: forall r a v. (HasCallStack, KnownDenseMatrix v r r a, Num a) => DenseMatrix v r r a\ndenseEye = runST $ do\n  let n = natToInt @r\n  cBuffer <- G.unsafeThaw $ G.replicate (n * n) (0 :: a)\n  loopM 0 (< n) (+ 1) $ \\i ->\n    GM.write cBuffer (i * n + i) (1 :: a)\n  c <- G.freeze cBuffer\n  pure $ DenseMatrix c\n\nisDenseMatrixDiagonal :: (KnownDenseMatrix v r r a, Eq a, Num a) => DenseMatrix v r r a -> Bool\nisDenseMatrixDiagonal matrix =\n  Data.Vector.Fusion.Util.unId\n    . Bundle.and\n    . Bundle.map (\\(i, x) -> x == 0 || i `mod` n == i `div` n)\n    . Bundle.indexed\n    . G.stream\n    . dmData\n    $ matrix\n  where\n    n = dmRows matrix\n\nisDenseMatrixSquare :: KnownDenseMatrix v r c a => DenseMatrix v r c a -> Bool\nisDenseMatrixSquare m = dmRows m == dmCols m\n\nisDenseMatrixEmpty :: KnownDenseMatrix v r c a => DenseMatrix v r c a -> Bool\nisDenseMatrixEmpty m = dmRows m * dmCols m == 0\n\nindexDenseMatrix :: (HasCallStack, KnownDenseMatrix v r c a) => DenseMatrix v r c a -> Int -> Int -> a\nindexDenseMatrix m i j = dmData m ! (c * i + j)\n  where\n    c = dmCols m\n\nisDenseMatrixHermitian :: (KnownDenseMatrix v r c (Complex a), Num a, Eq a) => DenseMatrix v r c (Complex a) -> Bool\nisDenseMatrixHermitian matrix = isDenseMatrixSquare matrix && go 0 0\n  where\n    (r, c) = dmShape matrix\n    -- Iterate over upper triangle (including the diagonal) of the matrix\n    go :: Int -> Int -> Bool\n    go !i !j\n      | j == c = let !i' = i + 1 in (i' >= r) || go i' i'\n      | otherwise =\n        let !p = indexDenseMatrix matrix i j == conjugate (indexDenseMatrix matrix j i)\n         in p && go i (j + 1)\n\ndenseMatrixFromList ::\n  forall r c a v.\n  (G.Vector v a, KnownNat r, KnownNat c) =>\n  [[a]] ->\n  Either Text (DenseMatrix v r c a)\ndenseMatrixFromList rs\n  | length rs /= natToInt @r = Left $ \"expected \" <> show (natToInt @r) <> \" rows\"\n  | any ((/= natToInt @c) . length) rs = Left $ \"expected \" <> show (natToInt @c) <> \" columns\"\n  | otherwise = Right . DenseMatrix . G.fromList . mconcat $ rs\n\ninstance (G.Vector v a, KnownNat r, KnownNat c) => GHC.IsList (DenseMatrix v r c a) where\n  type Item (DenseMatrix v r c a) = [a]\n  fromList rows = case denseMatrixFromList rows of\n    Right m -> m\n    Left msg -> error msg\n\ncooFromList ::\n  forall r c a i v.\n  (KnownCOO v i r c a, Integral i) =>\n  [(i, i, a)] ->\n  Either Text (COO v i r c a)\ncooFromList coordinates\n  | all valid coordinates = Right . COO . G.fromList $ coordinates\n  | otherwise = Left \"index out of bounds\"\n  where\n    valid (i, j, _) = 0 <= i && i < r && 0 <= j && j < c\n    r = fromIntegral $ natToInt @r\n    c = fromIntegral $ natToInt @c\n\ninstance (KnownCOO v i r c a, Integral i) => GHC.IsList (COO v i r c a) where\n  type Item (COO v i r c a) = (i, i, a)\n  fromList coordinates = case cooFromList coordinates of\n    Right m -> m\n    Left msg -> error msg\n\ninstance (KnownCSR v i r c a, Integral i, Num a) => GHC.IsList (CSR v i r c a) where\n  type Item (CSR v i r c a) = (i, i, a)\n  fromList coordinates = cooToCsr @Data.Vector.Vector @v $ fromList coordinates\n  toList = G.toList . cooData . csrToCoo @v @Data.Vector.Vector\n\ninstance (G.Vector v i, G.Vector v a, Integral i, Num a) => GHC.IsList (SomeCSR v i a) where\n  type Item (SomeCSR v i a) = (i, i, a)\n  fromList coordinates =\n    withSomeNat n $ \\(Proxy :: Proxy r) ->\n      withSomeNat m $ \\(Proxy :: Proxy c) ->\n        SomeCSR $ fromList @(CSR v i r c a) coordinates\n    where\n      (n, m) = computeShape (Data.Vector.fromList coordinates)\n\n-- data {-# CTYPE \"ls_bit_index\" #-} BitIndex = BitIndex !Word8 !Word8\n--   deriving stock (Show, Eq, Generic)\n\n--  deriving anyclass (Binary)\n\n-- instance Binary CUInt where\n--   put (CUInt x) = Data.Binary.put x\n--   get = CUInt <$> Data.Binary.get\n\n-- data SparseSquareMatrix = SparseSquareMatrix\n--   { ssmDimension :: {-# UNPACK #-} !Int,\n--     ssmOffsets :: {-# UNPACK #-} !(S.Vector CUInt),\n--     ssmColumns :: {-# UNPACK #-} !(S.Vector CUInt),\n--     ssmOffDiagElements :: {-# UNPACK #-} !(S.Vector (Complex Double)),\n--     ssmDiagElements :: {-# UNPACK #-} !(S.Vector (Complex Double))\n--   }\n--   deriving stock (Show, Eq, Generic)\n\n--   deriving anyclass (Binary)\n\n-- isSparseMatrixHermitian :: SparseSquareMatrix -> Bool\n-- isSparseMatrixHermitian = isDenseMatrixHermitian . sparseToDense\n\n-- withCsparse_matrix :: SparseSquareMatrix -> (Csparse_matrix -> IO a) -> IO a\n-- withCsparse_matrix matrix action =\n--   S.unsafeWith (scsrOffsets matrix) $ \\offsetsPtr ->\n--     S.unsafeWith (ssmColumns matrix) $ \\columnsPtr ->\n--       S.unsafeWith (ssmOffDiagElements matrix) $ \\offDiagElementsPtr ->\n--         S.unsafeWith (ssmDiagElements matrix) $ \\diagElementsPtr ->\n--           action $\n--             Csparse_matrix\n--               (fromIntegral . ssmDimension $ matrix)\n--               (fromIntegral . S.length . ssmColumns $ matrix)\n--               offsetsPtr\n--               columnsPtr\n--               offDiagElementsPtr\n--               diagElementsPtr\n\n-- typedef struct ls_csr_matrix {\n--     unsigned         dimension;\n--     unsigned         number_nonzero;\n--     unsigned*        offsets;\n--     unsigned*        columns;\n--     _Complex double* off_diag_elements;\n--     _Complex double* diag_elements;\n-- } ls_csr_matrix;\n-- data {-# CTYPE \"helpers.h\" \"ls_csr_matrix\" #-} Csparse_matrix\n--   = Csparse_matrix\n--       {-# UNPACK #-} !CUInt\n--       {-# UNPACK #-} !CUInt\n--       {-# UNPACK #-} !(Ptr CUInt)\n--       {-# UNPACK #-} !(Ptr CUInt)\n--       {-# UNPACK #-} !(Ptr (Complex Double))\n--       {-# UNPACK #-} !(Ptr (Complex Double))\n\n-- instance Storable Csparse_matrix where\n--   sizeOf _ = 40\n--   alignment _ = 8\n--   peek p =\n--     Csparse_matrix\n--       <$> peekByteOff p 0\n--       <*> peekByteOff p 4\n--       <*> peekByteOff p 8\n--       <*> peekByteOff p 16\n--       <*> peekByteOff p 24\n--       <*> peekByteOff p 32\n--   poke p (Csparse_matrix dimension number_nonzero offsets columns off_diag_elements diag_elements) = do\n--     pokeByteOff p 0 dimension\n--     pokeByteOff p 4 number_nonzero\n--     pokeByteOff p 8 offsets\n--     pokeByteOff p 16 columns\n--     pokeByteOff p 24 off_diag_elements\n--     pokeByteOff p 32 diag_elements\n\n-- trueCsparse_matrixSizeOf :: Int\n-- trueCsparse_matrixSizeOf = fromIntegral [CU.pure| unsigned int { sizeof(ls_csr_matrix) } |]\n\n-- trueCsparse_matrixAlignment :: Int\n-- trueCsparse_matrixAlignment = fromIntegral [CU.pure| unsigned int { __alignof__(ls_csr_matrix) } |]\n\n-- typedef struct ls_bit_index {\n--     uint8_t word;\n--     uint8_t bit;\n-- } ls_bit_index;\n-- data {-# CTYPE \"helpers.h\" \"ls_bit_index\" #-} Cbit_index\n--   = Cbit_index {-# UNPACK #-} !Word8 {-# UNPACK #-} !Word8\n--   deriving (Show, Eq, Generic)\n\n--  deriving anyclass (Binary)\n\n-- instance Storable Cbit_index where\n--   sizeOf _ = 2\n--   alignment _ = 1\n--   peek p = Cbit_index <$> peekByteOff p 0 <*> peekByteOff p 1\n--   poke p (Cbit_index word bit) = pokeByteOff p 0 word >> pokeByteOff p 1 bit\n\n-- trueCbit_indexSizeOf :: Int\n-- trueCbit_indexSizeOf = fromIntegral [CU.pure| unsigned int { sizeof(ls_bit_index) } |]\n\n-- trueCbit_indexAlignment :: Int\n-- trueCbit_indexAlignment = fromIntegral [CU.pure| unsigned int { __alignof__(ls_bit_index) } |]\n\n-- typedef unsigned (*ls_term_gather_fn)(uint64_t const* /*source*/, ls_bit_index const* /*tuple*/);\n-- typedef void (*ls_term_scatter_fn)(unsigned, ls_bit_index const* /*tuple*/,\n--                                    uint64_t* /*destination*/);\n-- typedef struct ls_term {\n--     ls_csr_matrix      matrix;\n--     unsigned           number_tuples;\n--     unsigned           tuple_size;\n--     ls_bit_index*      tuples;\n--     ls_term_gather_fn  gather_fn;\n--     ls_term_scatter_fn scatter_fn;\n-- } ls_term;\n-- data {-# CTYPE \"helpers.h\" \"ls_term\" #-} Cterm\n--   = Cterm\n--       {-# UNPACK #-} !Csparse_matrix\n--       {-# UNPACK #-} !CUInt\n--       {-# UNPACK #-} !CUInt\n--       {-# UNPACK #-} !(Ptr Cbit_index)\n--       {-# UNPACK #-} !(FunPtr (Ptr Word64 -> Ptr Cbit_index -> IO CUInt))\n--       {-# UNPACK #-} !(FunPtr (CUInt -> Ptr Cbit_index -> Ptr Word64 -> IO ()))\n\n-- instance Storable Cterm where\n--   sizeOf _ = 72\n--   alignment _ = 8\n--   peek p =\n--     Cterm\n--       <$> peekByteOff p 0\n--       <*> peekByteOff p 40\n--       <*> peekByteOff p 44\n--       <*> peekByteOff p 48\n--       <*> peekByteOff p 56\n--       <*> peekByteOff p 64\n--   poke p (Cterm matrix number_tuples tuple_size tuples gather_fn scatter_fn) = do\n--     pokeByteOff p 0 matrix\n--     pokeByteOff p 40 number_tuples\n--     pokeByteOff p 44 tuple_size\n--     pokeByteOff p 48 tuples\n--     pokeByteOff p 56 gather_fn\n--     pokeByteOff p 64 scatter_fn\n\n-- trueCtermSizeOf :: Int\n-- trueCtermSizeOf = fromIntegral [CU.pure| unsigned int { sizeof(ls_term) } |]\n\n-- trueCtermAlignment :: Int\n-- trueCtermAlignment = fromIntegral [CU.pure| unsigned int { __alignof__(ls_term) } |]\n\n-- data SitesList = SitesList\n--   { slNumberTuples :: !Int,\n--     slTupleSize :: !Int,\n--     slData :: !(S.Vector Cbit_index)\n--   }\n--   deriving stock (Show, Eq, Generic)\n\n--  deriving anyclass (Binary)\n\n-- sitesListFromList :: [[Int]] -> Either Text SitesList\n-- sitesListFromList rows = do\n--   (DenseMatrix (numberTuples, tupleSize) v) <- denseMatrixFromList rows\n--   when (S.any (< 0) v) $\n--     Left \"sites list cannot have negative elements\"\n--   when (S.any (> fromIntegral (maxBound :: Word16)) v) $\n--     Left \"sites list cannot such large elements\"\n--   Right $ SitesList numberTuples tupleSize (S.map toBitIndex v)\n--   where\n--     toBitIndex x = Cbit_index (fromIntegral (x `div` 64)) (fromIntegral (x `mod` 64))\n\n-- newtype SitesList = SitesList [[Int]]\n\n-- data OperatorTerm = OperatorTerm {otMatrix :: !SparseSquareMatrix, otSites :: !SitesList}\n--   deriving stock (Show, Eq, Generic)\n\n--  deriving anyclass (Binary)\n\n-- data {-# CTYPE \"ls_hs_operator_term\" #-} OperatorTermWrapper\n--   = OperatorTermWrapper\n--       {-# UNPACK #-} !(Ptr Cterm)\n--       {-# UNPACK #-} !(StablePtr OperatorTerm)\n\n-- instance Storable OperatorTermWrapper where\n--   {-# INLINE sizeOf #-}\n--   sizeOf _ = 16\n--   {-# INLINE alignment #-}\n--   alignment _ = 8\n--   {-# INLINE peek #-}\n--   peek p = OperatorTermWrapper <$> peekByteOff p 0 <*> peekByteOff p 8\n--   {-# INLINE poke #-}\n--   poke p (OperatorTermWrapper term stable) =\n--     pokeByteOff p 0 term >> pokeByteOff p 8 stable\n\n-- vectorFromPtr :: Storable a => Int -> Ptr a -> IO (S.Vector a)\n-- vectorFromPtr n p = S.freeze =<< SM.unsafeFromForeignPtr0 <$> newForeignPtr_ p <*> pure n\n\n-- denseMatrixFromPtr :: Int -> Int -> Ptr a -> IO (DenseMatrix v r c a)\n-- denseMatrixFromPtr = undefined\n\n-- ls_hs_create_operator_term_from_dense ::\n--   CUInt ->\n--   Ptr (Complex Double) ->\n--   CUInt ->\n--   CUInt ->\n--   Ptr Word16 ->\n--   IO (Ptr OperatorTermWrapper)\n-- ls_hs_create_operator_term_from_dense dimension matrixData numberTuples tupleSize tuplesData = do\n--   let dimension' = fromIntegral dimension\n--       numberTuples' = fromIntegral numberTuples\n--       tupleSize' = fromIntegral tupleSize\n--   matrixContents <- vectorFromPtr (dimension' * dimension') matrixData\n--   let matrix = case denseToSparse $ DenseMatrix (dimension', dimension') matrixContents of\n--         Right m -> m\n--         Left e -> error e\n--       toBitIndex x = Cbit_index (fromIntegral (x `div` 64)) (fromIntegral (x `mod` 64))\n--   sitesContents <- vectorFromPtr (numberTuples' * tupleSize') tuplesData\n--   let sites = SitesList numberTuples' tupleSize' (S.map toBitIndex sitesContents)\n--   when (2 ^ (slTupleSize sites) /= ssmDimension matrix) $\n--     error $ \"wrong matrix dimension\"\n--   let term = OperatorTerm matrix sites\n--   wrapper <- OperatorTermWrapper <$> allocateCterm term <*> newStablePtr term\n--   new wrapper\n\n-- allocateCterm :: OperatorTerm -> IO (Ptr Cterm)\n-- allocateCterm term = do\n--   p <- malloc\n--   withCterm term (poke p)\n--   return p\n\n-- deallocateCterm :: Ptr Cterm -> IO ()\n-- deallocateCterm p = free p\n\n-- allocateCterms :: NonEmpty OperatorTerm -> IO (Ptr Cterm)\n-- allocateCterms terms = do\n--   let !count = NonEmpty.length terms\n--       !elemSize = let x = x in sizeOf (x :: Cterm)\n--   p <- mallocBytes $ elemSize * count\n--   forM_ (NonEmpty.zip terms (fromList [0 ..])) $ \\(t, i) -> withCterm t (pokeElemOff p i)\n--   return p\n\n-- deallocateCterms :: Ptr Cterm -> IO ()\n-- deallocateCterms p = free p\n\n-- withCterm :: OperatorTerm -> (Cterm -> IO a) -> IO a\n-- withCterm (OperatorTerm matrix sites) action =\n--   withCsparse_matrix matrix $ \\matrix' ->\n--     S.unsafeWith (slData sites) $ \\tuplesPtr ->\n--       action $\n--         Cterm\n--           matrix'\n--           (fromIntegral . slNumberTuples $ sites)\n--           (fromIntegral . slTupleSize $ sites)\n--           tuplesPtr\n--           gatherPtr\n--           scatterPtr\n--   where\n--     (gatherPtr, scatterPtr) = case slTupleSize sites of\n--       1 -> (ls_internal_term_gather_1, ls_internal_term_scatter_1)\n--       2 -> (ls_internal_term_gather_2, ls_internal_term_scatter_2)\n--       3 -> (ls_internal_term_gather_3, ls_internal_term_scatter_3)\n--       4 -> (ls_internal_term_gather_4, ls_internal_term_scatter_4)\n--       _ -> error \"Oops!\"\n\n-- toOperatorTerm' :: InteractionSpec -> Either Text OperatorTerm\n-- toOperatorTerm' (InteractionSpec matrixSpec sitesSpec) = do\n--   sites <- sitesListFromList sitesSpec\n--   matrix <- denseToSparse =<< denseMatrixFromList matrixSpec\n--   when (2 ^ (slTupleSize sites) /= ssmDimension matrix) $\n--     Left $ \"wrong matrix dimension\"\n--   Right $ OperatorTerm matrix sites\n\n-- toOperatorTerm :: InteractionSpec -> OperatorTerm\n-- toOperatorTerm spec = case toOperatorTerm' spec of\n--   Right o -> o\n--   Left e -> error e\n\n-- foreign import capi \"helpers.h ls_hs_apply_term\"\n--   ls_hs_apply_term :: Ptr Cterm -> Ptr Word64 -> Ptr Coutput_buffer -> IO ()\n\n-- applyOperatorTerm' ::\n--   OperatorTerm ->\n--   [Word64] ->\n--   IO (S.Vector Word64, S.Vector (Complex Double), Complex Double)\n-- applyOperatorTerm' term bits =\n--   withCterm term $ \\term' -> with term' $ \\termPtr ->\n--     withArrayLen bits $ \\numberWords bitsPtr -> do\n--       outputSpins <- SM.new (bufferSize * numberWords)\n--       outputCoeffs <- SM.new bufferSize\n--       diagonal <- SM.unsafeWith outputSpins $ \\spinsPtr ->\n--         SM.unsafeWith outputCoeffs $ \\coeffsPtr ->\n--           alloca $ \\diagonalPtr -> do\n--             let (copyPtr, fillPtr) = case numberWords of\n--                   1 -> (ls_internal_spin_copy_1, ls_internal_spin_fill_1)\n--                 outputBuffer =\n--                   Coutput_buffer\n--                     spinsPtr\n--                     coeffsPtr\n--                     diagonalPtr\n--                     (fromIntegral numberWords)\n--                     copyPtr\n--                     fillPtr\n--             poke diagonalPtr 0\n--             with outputBuffer $ \\outPtr ->\n--               ls_hs_apply_term termPtr bitsPtr outPtr\n--             peek diagonalPtr\n--       (,,) <$> S.freeze outputSpins\n--         <*> S.freeze outputCoeffs\n--         <*> pure diagonal\n--   where\n--     bufferSize = estimateBufferSizeForTerm term\n\n-- applyOperatorTerm ::\n--   OperatorTerm ->\n--   Word64 ->\n--   (S.Vector Word64, S.Vector (Complex Double), Complex Double)\n-- applyOperatorTerm = undefined\n\n-- toOperator :: FlatSpinBasis -> OperatorSpec -> SparseOperator\n-- toOperator basis (OperatorSpec _ terms) = SparseOperator basis (toOperatorTerm <$> terms)\n\n-- typedef struct ls_output_buffer {\n--   uint64_t *spins;\n--   _Complex double *coeffs;\n--   _Complex double *const diagonal;\n--   uint64_t const number_words;\n--   ls_spin_copy_fn const spin_copy;\n--   ls_spin_fill_fn const spin_fill;\n-- } ls_output_buffer;\n-- data {-# CTYPE \"helpers.h\" \"ls_output_buffer\" #-} Coutput_buffer\n--   = Coutput_buffer\n--       {-# UNPACK #-} !(Ptr Word64)\n--       {-# UNPACK #-} !(Ptr (Complex Double))\n--       {-# UNPACK #-} !(Ptr (Complex Double))\n--       {-# UNPACK #-} !Word64\n--       {-# UNPACK #-} !(FunPtr Cspin_copy_fn)\n--       {-# UNPACK #-} !(FunPtr Cspin_fill_fn)\n\n-- type Cspin_copy_fn = Ptr Word64 -> Ptr Word64 -> IO ()\n\n-- type Cspin_fill_fn = Ptr Word64 -> Word64 -> Ptr Word64 -> IO ()\n\n-- instance Storable Coutput_buffer where\n--   sizeOf _ = 48\n--   alignment _ = 8\n--   peek p =\n--     Coutput_buffer\n--       <$> peekByteOff p 0\n--       <*> peekByteOff p 8\n--       <*> peekByteOff p 16\n--       <*> peekByteOff p 24\n--       <*> peekByteOff p 32\n--       <*> peekByteOff p 40\n--   poke p (Coutput_buffer spins coeffs diagonal number_words spin_copy spin_fill) = do\n--     pokeByteOff p 0 spins\n--     pokeByteOff p 8 coeffs\n--     pokeByteOff p 16 diagonal\n--     pokeByteOff p 24 number_words\n--     pokeByteOff p 32 spin_copy\n--     pokeByteOff p 40 spin_fill\n\n-- trueCoutput_bufferSizeOf :: Int\n-- trueCoutput_bufferSizeOf = fromIntegral [CU.pure| unsigned int { sizeof(ls_output_buffer) } |]\n\n-- trueCoutput_bufferAlignment :: Int\n-- trueCoutput_bufferAlignment = fromIntegral [CU.pure| unsigned int { __alignof__(ls_output_buffer) } |]\n\n-- data {-# CTYPE \"helpers.h\" \"ls_workspace\" #-} Cworkspace\n--   = Cworkspace\n--       {-# UNPACK #-} !(Ptr Word64)\n--       {-# UNPACK #-} !(Ptr (Complex Double))\n--       {-# UNPACK #-} !(Ptr Double)\n\n-- typedef struct ls_sparse_operator {\n--   ls_flat_spin_basis const *basis;\n--   unsigned number_terms;\n--   ls_term *terms;\n-- } ls_sparse_operator;\n-- data {-# CTYPE \"helpers.h\" \"ls_sparse_operator\" #-} Csparse_operator\n--   = Csparse_operator\n--       {-# UNPACK #-} !(Ptr CFlatSpinBasis)\n--       {-# UNPACK #-} !CUInt\n--       {-# UNPACK #-} !(Ptr Cterm)\n\n-- instance Storable Csparse_operator where\n--   sizeOf _ = 24\n--   alignment _ = 8\n--   peek p =\n--     Csparse_operator\n--       <$> peekByteOff p 0\n--       <*> peekByteOff p 8\n--       <*> peekByteOff p 16\n--   poke p (Csparse_operator basis number_terms terms) = do\n--     pokeByteOff p 0 basis\n--     pokeByteOff p 8 number_terms\n--     pokeByteOff p 16 terms\n\n-- trueCsparse_operatorSizeOf :: Int\n-- trueCsparse_operatorSizeOf = fromIntegral [CU.pure| unsigned int { sizeof(ls_sparse_operator) } |]\n\n-- trueCsparse_operatorAlignment :: Int\n-- trueCsparse_operatorAlignment = fromIntegral [CU.pure| unsigned int { __alignof__(ls_sparse_operator) } |]\n\n-- estimateBufferSizeForTerm :: OperatorTerm -> Int\n-- estimateBufferSizeForTerm (OperatorTerm matrix (SitesList numberTuples _ _)) =\n--   1 + maxNonZeroPerRow * numberTuples\n--   where\n--     maxNonZeroPerRow =\n--       if ssmDimension matrix /= 0\n--         then\n--           fromIntegral . S.maximum $\n--             S.generate\n--               (ssmDimension matrix)\n--               (\\i -> scsrOffsets matrix ! (i + 1) - scsrOffsets matrix ! i)\n--         else 0\n\n-- data SparseOperator = SparseOperator FlatSpinBasis (NonEmpty OperatorTerm)\n\n-- data SparseOperatorWrapper = SparseOperatorWrapper (Ptr Csparse_operator) (StablePtr SparseOperator)\n\n-- mkSparseOperator :: FlatSpinBasis -> NonEmpty OperatorTerm -> SparseOperator\n-- mkSparseOperator = SparseOperator\n\n-- allocateCsparse_operator :: SparseOperator -> IO (Ptr Csparse_operator)\n-- allocateCsparse_operator (SparseOperator (FlatSpinBasis basis) terms) = do\n--   termsPtr <- allocateCterms terms\n--   new $\n--     Csparse_operator\n--       (unsafeForeignPtrToPtr basis)\n--       (fromIntegral $ NonEmpty.length terms)\n--       termsPtr\n\n-- deallocateCsparse_operator :: Ptr Csparse_operator -> IO ()\n-- deallocateCsparse_operator p = do\n--   (Csparse_operator _ _ termsPtr) <- peek p\n--   deallocateCterms termsPtr\n--   free p\n\n-- allocateCsparse_operator ::\n\n-- instance Storable SparseSquareMatrix where\n--   sizeOf _ = 16\n--   alignment _ = 4\n--   peek p =\n--     HalideDimension\n--       <$> peekByteOff p 0\n--       <*> peekByteOff p 4\n--       <*> peekByteOff p 8\n--       <*> peekByteOff p 12\n--   poke p x = do\n--     pokeByteOff p 0 (halideDimensionMin x)\n--     pokeByteOff p 4 (halideDimensionExtent x)\n--     pokeByteOff p 8 (halideDimensionStride x)\n--     pokeByteOff p 12 (halideDimensionFlags x)\n\n-- denseMatrixCountNonZero :: (Storable a, Eq a, Num a) => DenseMatrix v r c a -> Int\n-- denseMatrixCountNonZero matrix = S.foldl' (\\(!n) !x -> if x /= 0 then n + 1 else n) 0 (denseMatrixData matrix)\n\n-- for (auto i = 0; i < numberRows; ++i) {\n--   unsigned numberNonZero = 0;\n--   for (auto j = 0; j < numberColumns; ++j) {\n--     if (dense[i, j] != 0 && i != j) {\n--       ++numberNonZero;\n--       *(columns++) = j;\n--       *(off_diag_elements++) = dense[i, j];\n--     }\n--   }\n--   offsets[i + 1] = offsets[i] + numberNonZero;\n-- }\n\n-- denseToSparse :: DenseMatrix (Complex Double) -> Either Text SparseSquareMatrix\n-- denseToSparse dense\n--   | isDenseMatrixSquare dense = Right $\n--     System.IO.Unsafe.unsafePerformIO $\n--       do\n--         let numberNonZero = denseMatrixCountNonZero dense\n--             dimension = let (DenseMatrix (n, _) _) = dense in n\n--         offsets <- SM.new (dimension + 1)\n--         columns <- SM.new numberNonZero\n--         offDiagElements <- SM.new numberNonZero\n--         diagElements <- SM.new dimension\n--         S.unsafeWith (denseMatrixData dense) $ \\c_dense ->\n--           SM.unsafeWith offsets $ \\c_offsets ->\n--             SM.unsafeWith columns $ \\c_columns ->\n--               SM.unsafeWith offDiagElements $ \\c_off_diag_elements ->\n--                 SM.unsafeWith diagElements $ \\c_diag_elements ->\n--                   ls_csr_matrix_from_dense\n--                     (fromIntegral dimension)\n--                     c_dense\n--                     c_offsets\n--                     c_columns\n--                     c_off_diag_elements\n--                     c_diag_elements\n--         numberNonZero' <- fromIntegral <$> SM.read offsets dimension\n--         SparseSquareMatrix dimension\n--           <$> S.freeze offsets\n--           <*> S.freeze (SM.take numberNonZero' columns)\n--           <*> S.freeze (SM.take numberNonZero' offDiagElements)\n--           <*> S.freeze diagElements\n--   | otherwise = Left \"expected a square matrix\"\n\n{- ORMOLU_DISABLE -}\n-- foreign import capi unsafe \"helpers.h ls_csr_matrix_from_dense\"\n--   ls_csr_matrix_from_dense :: CUInt -> Ptr (Complex Double) -> Ptr CUInt -> Ptr CUInt ->\n--                               Ptr (Complex Double) -> Ptr (Complex Double) -> IO ()\n\n-- foreign import capi unsafe \"helpers.h ls_dense_from_csr_matrix\"\n--   ls_dense_from_csr_matrix :: CUInt -> Ptr CUInt -> Ptr CUInt -> Ptr (Complex Double) ->\n--                               Ptr (Complex Double) -> Ptr (Complex Double) -> IO ()\n{- ORMOLU_ENABLE -}\n\n-- sparseToDense :: SparseSquareMatrix -> DenseMatrix (Complex Double)\n-- sparseToDense sparse = System.IO.Unsafe.unsafePerformIO $ do\n--   let dimension = ssmDimension sparse\n--   elements <- SM.new (dimension * dimension)\n--   S.unsafeWith (scsrOffsets sparse) $ \\c_offsets ->\n--     S.unsafeWith (ssmColumns sparse) $ \\c_columns ->\n--       S.unsafeWith (ssmOffDiagElements sparse) $ \\c_off_diag_elements ->\n--         S.unsafeWith (ssmDiagElements sparse) $ \\c_diag_elements ->\n--           SM.unsafeWith elements $ \\c_dense ->\n--             ls_dense_from_csr_matrix\n--               (fromIntegral dimension)\n--               c_offsets\n--               c_columns\n--               c_off_diag_elements\n--               c_diag_elements\n--               c_dense\n--   DenseMatrix (dimension, dimension) <$> S.freeze elements\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_term_gather_1\"\n--   ls_internal_term_gather_1 :: FunPtr (Ptr Word64 -> Ptr Cbit_index -> IO CUInt)\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_term_gather_2\"\n--   ls_internal_term_gather_2 :: FunPtr (Ptr Word64 -> Ptr Cbit_index -> IO CUInt)\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_term_gather_3\"\n--   ls_internal_term_gather_3 :: FunPtr (Ptr Word64 -> Ptr Cbit_index -> IO CUInt)\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_term_gather_4\"\n--   ls_internal_term_gather_4 :: FunPtr (Ptr Word64 -> Ptr Cbit_index -> IO CUInt)\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_term_scatter_1\"\n--   ls_internal_term_scatter_1 :: FunPtr (CUInt -> Ptr Cbit_index -> Ptr Word64 -> IO ())\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_term_scatter_2\"\n--   ls_internal_term_scatter_2 :: FunPtr (CUInt -> Ptr Cbit_index -> Ptr Word64 -> IO ())\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_term_scatter_3\"\n--   ls_internal_term_scatter_3 :: FunPtr (CUInt -> Ptr Cbit_index -> Ptr Word64 -> IO ())\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_term_scatter_4\"\n--   ls_internal_term_scatter_4 :: FunPtr (CUInt -> Ptr Cbit_index -> Ptr Word64 -> IO ())\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_spin_copy_1\"\n--   ls_internal_spin_copy_1 :: FunPtr (Ptr Word64 -> Ptr Word64 -> IO ())\n\n-- foreign import capi unsafe \"helpers.h &ls_internal_spin_fill_1\"\n--   ls_internal_spin_fill_1 :: FunPtr (Ptr Word64 -> Word64 -> Ptr Word64 -> IO ())\n", "meta": {"hexsha": "9f605d2414f4c2cd3a2a6474d769e18e02085106", "size": 53352, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/LatticeSymmetries/Sparse.hs", "max_stars_repo_name": "twesterhout/lattice-symmetries-haskell", "max_stars_repo_head_hexsha": "812bf24d400d727a217a450171915c216c45c88e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LatticeSymmetries/Sparse.hs", "max_issues_repo_name": "twesterhout/lattice-symmetries-haskell", "max_issues_repo_head_hexsha": "812bf24d400d727a217a450171915c216c45c88e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LatticeSymmetries/Sparse.hs", "max_forks_repo_name": "twesterhout/lattice-symmetries-haskell", "max_forks_repo_head_hexsha": "812bf24d400d727a217a450171915c216c45c88e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6177076184, "max_line_length": 116, "alphanum_fraction": 0.600108712, "num_tokens": 16151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.1931938363429014}}
{"text": "{-# LANGUAGE CPP #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n#if __GLASGOW_HASKELL__ >= 702\n{-# LANGUAGE Trustworthy #-}\n#endif\n\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Data.Distributive\n-- Copyright   :  (C) 2011-2016 Edward Kmett\n-- License     :  BSD-style (see the file LICENSE)\n--\n-- Maintainer  :  Edward Kmett <ekmett@gmail.com>\n-- Stability   :  provisional\n-- Portability :  portable\n--\n----------------------------------------------------------------------------\nmodule Data.Distributive\n  ( Distributive(..)\n  , cotraverse\n  , comapM\n  , fmapCollect\n  ) where\n\nimport Control.Applicative\nimport Control.Applicative.Backwards\nimport Control.Monad (liftM)\n#if __GLASGOW_HASKELL__ < 707\nimport Control.Monad.Instances ()\n#endif\nimport Control.Monad.Trans.Identity\nimport Control.Monad.Trans.Reader\nimport Data.Coerce\nimport Data.Functor.Compose\nimport Data.Functor.Identity\nimport Data.Functor.Product\nimport Data.Functor.Reverse\nimport qualified Data.Monoid as Monoid\nimport Data.Orphans ()\n\n#if MIN_VERSION_base(4,4,0)\nimport Data.Complex\n#endif\n#if __GLASGOW_HASKELL__ >= 707 || defined(MIN_VERSION_tagged)\nimport Data.Proxy\n#endif\n#if __GLASGOW_HASKELL__ >= 800 || defined(MIN_VERSION_semigroups)\nimport qualified Data.Semigroup as Semigroup\n#endif\n#ifdef MIN_VERSION_tagged\nimport Data.Tagged\n#endif\n#if __GLASGOW_HASKELL__ >= 702\nimport GHC.Generics (U1(..), (:*:)(..), (:.:)(..), Par1(..), Rec1(..), M1(..))\n#endif\n\n#ifdef HLINT\n{-# ANN module \"hlint: ignore Use section\" #-}\n#endif\n\n-- | This is the categorical dual of 'Traversable'.\n--\n-- Due to the lack of non-trivial comonoids in Haskell, we can restrict\n-- ourselves to requiring a 'Functor' rather than\n-- some Coapplicative class. Categorically every 'Distributive'\n-- functor is actually a right adjoint, and so it must be 'Representable'\n-- endofunctor and preserve all limits. This is a fancy way of saying it\n-- isomorphic to @(->) x@ for some x.\n--\n-- To be distributable a container will need to have a way to consistently\n-- zip a potentially infinite number of copies of itself. This effectively\n-- means that the holes in all values of that type, must have the same\n-- cardinality, fixed sized vectors, infinite streams, functions, etc.\n-- and no extra information to try to merge together.\n--\nclass Functor g => Distributive g where\n#if __GLASGOW_HASKELL__ >= 707\n  {-# MINIMAL distribute | collect #-}\n#endif\n  -- | The dual of 'Data.Traversable.sequenceA'\n  --\n  -- >>> distribute [(+1),(+2)] 1\n  -- [2,3]\n  --\n  -- @\n  -- 'distribute' = 'collect' 'id'\n  -- 'distribute' . 'distribute' = 'id'\n  -- @\n  distribute  :: Functor f => f (g a) -> g (f a)\n  distribute  = collect id\n\n  -- |\n  -- @\n  -- 'collect' f = 'distribute' . 'fmap' f\n  -- 'fmap' f = 'runIdentity' . 'collect' ('Identity' . f)\n  -- 'fmap' 'distribute' . 'collect' f = 'getCompose' . 'collect' ('Compose' . f)\n  -- @\n\n  collect     :: Functor f => (a -> g b) -> f a -> g (f b)\n  collect f   = distribute . fmap f\n\n  -- | The dual of 'Data.Traversable.sequence'\n  --\n  -- @\n  -- 'distributeM' = 'fmap' 'unwrapMonad' . 'distribute' . 'WrapMonad'\n  -- @\n  distributeM :: Monad m => m (g a) -> g (m a)\n  distributeM = fmap unwrapMonad . distribute . WrapMonad\n\n  -- |\n  -- @\n  -- 'collectM' = 'distributeM' . 'liftM' f\n  -- @\n  collectM    :: Monad m => (a -> g b) -> m a -> g (m b)\n  collectM f  = distributeM . liftM f\n\n-- | The dual of 'Data.Traversable.traverse'\n--\n-- @\n-- 'cotraverse' f = 'fmap' f . 'distribute'\n-- @\ncotraverse :: (Distributive g, Functor f) => (f a -> b) -> f (g a) -> g b\ncotraverse f = fmap f . distribute\n\n-- | The dual of 'Data.Traversable.mapM'\n--\n-- @\n-- 'comapM' f = 'fmap' f . 'distributeM'\n-- @\ncomapM :: (Distributive g, Monad m) => (m a -> b) -> m (g a) -> g b\ncomapM f = fmap f . distributeM\n\ninstance Distributive Identity where\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall a b f . Functor f => (a -> Identity b) -> f a -> Identity (f b)\n  distribute = Identity . fmap runIdentity\n\n#if __GLASGOW_HASKELL__ >= 707 || defined(MIN_VERSION_tagged)\ninstance Distributive Proxy where\n  collect _ _ = Proxy\n  distribute _ = Proxy\n#endif\n\n#if defined(MIN_VERSION_tagged)\ninstance Distributive (Tagged t) where\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall a b f . Functor f => (a -> Tagged t b) -> f a -> Tagged t (f b)\n  distribute = Tagged . fmap unTagged\n#endif\n\ninstance Distributive ((->)e) where\n  distribute a e = fmap ($e) a\n  collect f q e = fmap (flip f e) q\n\ninstance Distributive g => Distributive (ReaderT e g) where\n  distribute a = ReaderT $ \\e -> collect (flip runReaderT e) a\n  collect f x = ReaderT $ \\e -> collect (\\a -> runReaderT (f a) e) x\n\ninstance Distributive g => Distributive (IdentityT g) where\n  collect = coerce (collect :: (a -> g b) -> f a -> g (f b))\n            :: forall a b f . Functor f => (a -> IdentityT g b) -> f a -> IdentityT g (f b)\n\ninstance (Distributive f, Distributive g) => Distributive (Compose f g) where\n  distribute = Compose . fmap distribute . collect getCompose\n  collect f = Compose . fmap distribute . collect (coerce f)\n\ninstance (Distributive f, Distributive g) => Distributive (Product f g) where\n  -- It might be tempting to write a 'collect' implementation that\n  -- composes the passed function with fstP and sndP. This could be bad,\n  -- because it would lead to the passed function being evaluated twice\n  -- for each element of the underlying functor.\n  distribute wp = Pair (collect fstP wp) (collect sndP wp) where\n    fstP (Pair a _) = a\n    sndP (Pair _ b) = b\n\n\ninstance Distributive f => Distributive (Backwards f) where\n  distribute = Backwards . collect forwards\n  collect = coerce (collect :: (a -> f b) -> g a -> f (g b))\n    :: forall g a b . Functor g\n    => (a -> Backwards f b) -> g a -> Backwards f (g b)\n\ninstance Distributive f => Distributive (Reverse f) where\n  distribute = Reverse . collect getReverse\n  collect = coerce (collect :: (a -> f b) -> g a -> f (g b))\n    :: forall g a b . Functor g\n    => (a -> Reverse f b) -> g a -> Reverse f (g b)\n\ninstance Distributive Monoid.Dual where\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall f a b . Functor f\n    => (a -> Monoid.Dual b) -> f a -> Monoid.Dual (f b)\n  distribute = Monoid.Dual . fmap Monoid.getDual\n\ninstance Distributive Monoid.Product where\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall f a b . Functor f\n    => (a -> Monoid.Product b) -> f a -> Monoid.Product (f b)\n  distribute = Monoid.Product . fmap Monoid.getProduct\n\ninstance Distributive Monoid.Sum where\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall f a b . Functor f\n    => (a -> Monoid.Sum b) -> f a -> Monoid.Sum (f b)\n  distribute = Monoid.Sum . fmap Monoid.getSum\n\n#if __GLASGOW_HASKELL__ >= 800 || defined(MIN_VERSION_semigroups)\ninstance Distributive Semigroup.Min where\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall f a b . Functor f\n    => (a -> Semigroup.Min b) -> f a -> Semigroup.Min (f b)\n  distribute = Semigroup.Min . fmap Semigroup.getMin\n\ninstance Distributive Semigroup.Max where\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall f a b . Functor f\n    => (a -> Semigroup.Max b) -> f a -> Semigroup.Max (f b)\n  distribute = Semigroup.Max . fmap Semigroup.getMax\n\ninstance Distributive Semigroup.First where\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall f a b . Functor f\n    => (a -> Semigroup.First b) -> f a -> Semigroup.First (f b)\n  distribute = Semigroup.First . fmap Semigroup.getFirst\n\ninstance Distributive Semigroup.Last where\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall f a b . Functor f\n    => (a -> Semigroup.Last b) -> f a -> Semigroup.Last (f b)\n  distribute = Semigroup.Last . fmap Semigroup.getLast\n#endif\n\n#if MIN_VERSION_base(4,4,0)\ninstance Distributive Complex where\n  distribute wc = fmap realP wc :+ fmap imagP wc where\n    -- Redefine realPart and imagPart to avoid incurring redundant RealFloat\n    -- constraints on older versions of base\n    realP (r :+ _) = r\n    imagP (_ :+ i) = i\n#endif\n\n-- | 'fmapCollect' is a viable default definition for 'fmap' given\n-- a 'Distributive' instance defined in terms of 'collect'.\nfmapCollect :: forall f a b . Distributive f => (a -> b) -> f a -> f b\nfmapCollect = coerce (collect :: (a -> Identity b) -> f a -> Identity (f b))\n\n#if __GLASGOW_HASKELL__ >= 702\ninstance Distributive U1 where\n  distribute _ = U1\n\ninstance (Distributive a, Distributive b) => Distributive (a :*: b) where\n  -- It might be tempting to write a 'collect' implementation that\n  -- composes the passed function with fstP and sndP. This could be bad,\n  -- because it would lead to the passed function being evaluated twice\n  -- for each element of the underlying functor.\n  distribute f = collect fstP f :*: collect sndP f where\n    fstP (l :*: _) = l\n    sndP (_ :*: r) = r\n\ninstance (Distributive a, Distributive b) => Distributive (a :.: b) where\n  distribute = Comp1 . fmap distribute . collect unComp1\n  collect f = Comp1 . fmap distribute . collect (coerce f)\n\ninstance Distributive Par1 where\n  distribute = Par1 . fmap unPar1\n  collect = coerce (fmap :: (a -> b) -> f a -> f b)\n    :: forall f a b . Functor f => (a -> Par1 b) -> f a -> Par1 (f b)\n\ninstance Distributive f => Distributive (Rec1 f) where\n  distribute = Rec1 . collect unRec1\n  collect = coerce (collect :: (a -> f b) -> g a -> f (g b))\n    :: forall g a b . Functor g\n    => (a -> Rec1 f b) -> g a -> Rec1 f (g b)\n\ninstance Distributive f => Distributive (M1 i c f) where\n  distribute = M1 . collect unM1\n  collect = coerce (collect :: (a -> f b) -> g a -> f (g b))\n    :: forall g a b . Functor g\n    => (a -> M1 i c f b) -> g a -> M1 i c f (g b)\n#endif\n", "meta": {"hexsha": "235641caefb2f497f2c42b9ffdc671a840a62181", "size": 9870, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Distributive.hs", "max_stars_repo_name": "aaronvargo/distributive", "max_stars_repo_head_hexsha": "02597df26da86a5bd4f5c436f122bcb7d8418f6b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Distributive.hs", "max_issues_repo_name": "aaronvargo/distributive", "max_issues_repo_head_hexsha": "02597df26da86a5bd4f5c436f122bcb7d8418f6b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Distributive.hs", "max_forks_repo_name": "aaronvargo/distributive", "max_forks_repo_head_hexsha": "02597df26da86a5bd4f5c436f122bcb7d8418f6b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8763250883, "max_line_length": 91, "alphanum_fraction": 0.6375886525, "num_tokens": 2928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.19233998538149177}}
{"text": "{-# LANGUAGE ApplicativeDo                        #-}\n{-# LANGUAGE DataKinds                            #-}\n{-# LANGUAGE DeriveFunctor                        #-}\n{-# LANGUAGE DeriveGeneric                        #-}\n{-# LANGUAGE FlexibleContexts                     #-}\n{-# LANGUAGE FlexibleInstances                    #-}\n{-# LANGUAGE FunctionalDependencies               #-}\n{-# LANGUAGE GADTs                                #-}\n{-# LANGUAGE KindSignatures                       #-}\n{-# LANGUAGE LambdaCase                           #-}\n{-# LANGUAGE MultiParamTypeClasses                #-}\n{-# LANGUAGE OverloadedStrings                    #-}\n{-# LANGUAGE PartialTypeSignatures                #-}\n{-# LANGUAGE PolyKinds                            #-}\n{-# LANGUAGE RankNTypes                           #-}\n{-# LANGUAGE RecordWildCards                      #-}\n{-# LANGUAGE ScopedTypeVariables                  #-}\n{-# LANGUAGE StandaloneDeriving                   #-}\n{-# LANGUAGE TemplateHaskell                      #-}\n{-# LANGUAGE TupleSections                        #-}\n{-# LANGUAGE TypeApplications                     #-}\n{-# LANGUAGE TypeFamilies                         #-}\n{-# LANGUAGE TypeOperators                        #-}\n{-# LANGUAGE TypeSynonymInstances                 #-}\n{-# LANGUAGE UndecidableInstances                 #-}\n{-# LANGUAGE ViewPatterns                         #-}\n{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}\n\nmodule Egg.Research (\n    BonusAmount(..), AsBonusAmount(..)\n  , BonusType(..), AsBonusType(..)\n  , Bonuses(..), _Bonuses\n  , Research(..), HasResearch(..)\n  , ResearchTier(..), rtUnlock, rtTechs, SomeResearchTier\n  , ResearchData(..), rdCommon, rdEpic, SomeResearchData\n  , ResearchStatus(..), rsCommon, rsEpic, SomeResearchStatus\n  , ResearchIx(..), _RICommon, _RIEpic\n  , ResearchError(..), _REMaxedOut, _RELocked\n  , scaleAmount\n  , hasEffect\n  , bonusEffect\n  , bonusEffectFor\n  , bonusing\n  , bonusingFor\n  , emptyBonuses\n  , bonuses\n  , maxLevel\n  , emptyResearchStatus\n  , researchBonuses\n  , totalBonuses\n  , researchCount\n  , legalTiers\n  , foldResearch\n  , purchaseResearch\n  , researchIxNum\n  , researchIxData\n  , researchIxStatus\n  , researchIxStatusLegal\n  , withSomeResearch\n  , researchIxesCommon\n  , researchIxesEpic\n  , legalResearchIxesCommon\n  , legalResearchIxesEpic\n  , legalResearchesCommon\n  , legalResearchesEpic\n  -- * Why?\n  , rdrsCommon\n  , rdrsEpic\n  , researchIx\n  ) where\n\nimport           Control.Applicative hiding      (some)\nimport           Control.Lens hiding             ((.=), (:<), Index)\nimport           Data.Aeson.Encoding\nimport           Data.Aeson.Types\nimport           Data.Bifunctor\nimport           Data.Dependent.Sum\nimport           Data.Finite\nimport           Data.Foldable\nimport           Data.Kind\nimport           Data.Maybe\nimport           Data.Monoid                     (First(..))\nimport           Data.Singletons\nimport           Data.Singletons.Prelude hiding  (Flip)\nimport           Data.Singletons.TypeLits\nimport           Data.Type.Combinator\nimport           Data.Type.Combinator.Singletons\nimport           Data.Type.Combinator.Util\nimport           Data.Type.Conjunction\nimport           Data.Type.Index\nimport           Data.Type.Product               as TCP\nimport           Data.Type.Sum\nimport           Data.Type.Vector\nimport           Data.Vector.Sized.Util\nimport           Egg.Commodity\nimport           GHC.Generics                    (Generic)\nimport           Numeric.Lens\nimport           Numeric.Natural\nimport           Statistics.LinearRegression\nimport           Type.Class.Higher\nimport           Type.Class.Witness\nimport           Type.Family.Tuple\nimport qualified Data.Map                        as M\nimport qualified Data.Text                       as T\nimport qualified Data.Vector                     as V\nimport qualified Data.Vector.Sized               as SV\n\ndata BonusAmount\n    -- | Bonus adds an absolute amount.  Scales by multiplication, and\n    -- compounds by addition.\n    = BAIncrement Double\n    -- | Bonus adds a percentage point multiplier.  Scales by\n    -- multiplication (three 10% buffs is a 15% buff) and compounds by\n    -- appropriate multiplication.\n    | BAPercent Double\n    -- | Bonus multiplies by a given ratio.  Scales by exponentiation\n    -- (three 2x buffs is a 8x buff) and compounds by multiplication.\n    | BAMultiplier Double\n  deriving (Show, Eq, Ord, Generic)\n\nmakeClassyPrisms ''BonusAmount\n\ndata BonusType =\n        BTBuildCosts\n      | BTDroneRewards\n      | BTEggValue\n      | BTFarmValue\n      | BTFleetSize\n      | BTHabCapacity\n      | BTHatcheryCapacity\n      | BTHatcheryRate\n      | BTHoldingHatch\n      | BTHoverVehicleCapacity\n      | BTInternalHatchery\n      | BTInternalHatcheryCalm\n      | BTInternalHatcherySharing\n      | BTLayingRate\n      | BTLongWarpTime\n      | BTMaxRunningBonus\n      | BTPrestigeEggs\n      | BTResearchCosts\n      | BTRunningBonus\n      | BTSiloQuality\n      | BTSoulEggBonus\n      | BTVehicleCapacity\n      | BTVehicleCosts\n      | BTVideoDoublerTime\n      | BTVehicleSpeed\n  deriving (Show, Eq, Ord, Generic)\n\nmakeClassyPrisms ''BonusType\n\nnewtype Bonuses = Bonuses { _bMap :: M.Map BonusType [BonusAmount] }\n    deriving (Show, Eq, Ord)\n\nmakePrisms ''Bonuses\nmakeWrapped ''Bonuses\n\ndata Research a =\n    Research { _rName        :: T.Text\n             , _rDescription :: T.Text\n             , _rBaseBonuses :: Bonuses\n             , _rCosts       :: V.Vector (Maybe a)\n             }\n  deriving (Show, Eq, Ord, Generic, Functor)\n\nmakeClassy ''Research\n\ndata ResearchTier :: Nat -> Type where\n    ResearchTier\n        :: { _rtUnlock :: Natural\n           , _rtTechs  :: SV.Vector n (Research Bock)\n           }\n        -> ResearchTier n\n  deriving (Show, Eq, Ord, Generic)\n\nmakeLenses ''ResearchTier\n\ntype SomeResearchTier = DSum Sing ResearchTier\n\ndata ResearchData :: [Nat] -> Nat -> Type where\n    ResearchData\n        :: { _rdCommon :: Prod ResearchTier tiers\n           , _rdEpic   :: SV.Vector epic (Research GoldenEgg)\n           }\n        -> ResearchData tiers epic\n  deriving (Show, Eq, Ord)\n\nmakeLenses ''ResearchData\n\ntype SomeResearchData = DSum Sing (Uncur ResearchData)\n\ndata ResearchStatus :: [Nat] -> Nat -> Type where\n    ResearchStatus\n        :: { _rsCommon :: Prod (Flip SV.Vector Natural) tiers\n           , _rsEpic   :: SV.Vector epic Natural\n           }\n        -> ResearchStatus tiers epic\n  deriving (Show, Eq, Ord, Generic)\n\nmakeLenses ''ResearchStatus\n\n\ntype SomeResearchStatus = DSum Sing (Uncur ResearchStatus)\n\n-- | A safe index for a given research item, usable with 'ResearchData' and\n-- 'ResearchStatus'.\ndata ResearchIx :: [Nat] -> Nat -> Type -> Type where\n    RICommon :: Sum Finite tiers -> ResearchIx tiers epic Bock\n    RIEpic   :: Finite epic      -> ResearchIx tiers epic GoldenEgg\n\nderiving instance Show (Sum Finite tiers) => Show (ResearchIx tiers epic a)\n\n_RICommon :: Iso (ResearchIx t1 epic Bock) (ResearchIx t2 epic Bock)\n                 (Sum Finite t1          ) (Sum Finite t2          )\n_RICommon = iso (\\case RICommon i -> i) RICommon\n\n_RIEpic :: Iso (ResearchIx tiers e1 GoldenEgg) (ResearchIx tiers e2 GoldenEgg)\n               (Finite e1                    ) (Finite e2                    )\n_RIEpic = iso (\\case RIEpic i -> i) RIEpic\n\nbonusAmountParseOptions :: Options\nbonusAmountParseOptions = defaultOptions\n    { sumEncoding = TaggedObject\n                      { tagFieldName      = \"type\"\n                      , contentsFieldName = \"value\"\n                      }\n    , constructorTagModifier = camelTo2 '-' . drop 2\n    }\n\ninstance FromJSON BonusAmount where\n    parseJSON  = genericParseJSON  bonusAmountParseOptions\ninstance ToJSON BonusAmount where\n    toJSON     = genericToJSON     bonusAmountParseOptions\n    toEncoding = genericToEncoding bonusAmountParseOptions\n\nbonusTypeParseOptions :: Options\nbonusTypeParseOptions = defaultOptions\n    { sumEncoding = UntaggedValue\n    , constructorTagModifier = camelTo2 '-' . drop 2\n    }\n\ninstance FromJSON BonusType where\n    parseJSON  = genericParseJSON  bonusTypeParseOptions\ninstance ToJSON BonusType where\n    toJSON     = genericToJSON     bonusTypeParseOptions\n    toEncoding = genericToEncoding bonusTypeParseOptions\ninstance FromJSONKey BonusType where\n    fromJSONKey = FromJSONKeyTextParser (parseJSON . String)\ninstance ToJSONKey BonusType where\n    toJSONKey = toJSONKeyText $\n        T.pack . constructorTagModifier bonusTypeParseOptions . show\n\ninstance Semigroup Bonuses where\n    (<>) = mappend\n\ninstance Monoid Bonuses where\n    mempty = Bonuses M.empty\n    mappend (Bonuses x) (Bonuses y) =\n      Bonuses (M.unionWith (++) x y)\n\ninstance (FromJSON a, RealFrac a) => FromJSON (Research a) where\n    parseJSON = withObject \"Research\" $ \\v ->\n        Research <$> v .: \"name\"\n                 <*> v .: \"description\"\n                 <*> (mkBase =<< v .: \"bonuses\")\n                 <*> (mkCosts <$> (v .:? \"costs\") <*> (v .:? \"levels\"))\n      where\n        mkBase :: M.Map BonusType Object -> Parser Bonuses\n        mkBase = fmap (Bonuses . fmap (:[])) . traverse (.: \"base-amount\")\n        mkCosts :: Maybe [a] -> Maybe Natural -> V.Vector (Maybe a)\n        mkCosts Nothing        Nothing  = V.empty\n        mkCosts Nothing        (Just l) = V.replicate (fromIntegral l) Nothing\n        mkCosts (Just [] )     (Just l) = V.replicate (fromIntegral l) Nothing\n        mkCosts (Just v  )     Nothing  = Just <$> V.fromList v\n        mkCosts (Just [x])     (Just l) = Just x `V.cons` V.replicate (fromIntegral l - 1) Nothing\n        mkCosts (Just v@(_:_)) (Just l) = Just <$> V.fromList v V.++ extras\n          where\n            lv = length v\n            extras = V.generate (fromIntegral l - lv) $ \\i -> realToFrac . exp $\n              \u03b1 + \u03b2 * fromIntegral (i + lv)\n            (\u03b1, \u03b2) = linearRegression (V.fromList $ zipWith const [0..] v)\n                                      (V.fromList (log . realToFrac <$> v))\n\ninstance ToJSON a => ToJSON (Research a) where\n    toJSON Research{..} = object $\n        [ \"name\"        .= _rName\n        , \"description\" .= _rDescription\n        , \"bonuses\"     .= object [ \"base-amount\" .= _bMap _rBaseBonuses ]\n        ] ++ case sequence _rCosts of\n            Just v  ->   [ \"costs\"  .= v ]\n            Nothing -> case sequence (V.takeWhile isJust _rCosts) of\n              Nothing -> [ \"levels\" .= V.length _rCosts ]\n              Just v  -> [ \"costs\"  .= v\n                         , \"levels\" .= V.length _rCosts\n                         ]\n    toEncoding Research{..} = pairs . mconcat $\n        [ \"name\"        .= _rName\n        , \"description\" .= _rDescription\n        , pair \"bonuses\" (pairs (\"base-amount\" .= _bMap _rBaseBonuses))\n        ] ++ case sequence _rCosts of\n            Just v  ->   [ \"costs\"  .= v ]\n            Nothing -> case sequence (V.takeWhile isJust _rCosts) of\n              Nothing -> [ \"levels\" .= V.length _rCosts ]\n              Just v  -> [ \"costs\"  .= v\n                         , \"levels\" .= V.length _rCosts\n                         ]\n\nresearchTierParseOptions :: Options\nresearchTierParseOptions = defaultOptions\n    { fieldLabelModifier = camelTo2 '-' . drop 3\n    }\n\ninstance KnownNat n => FromJSON (ResearchTier n) where\n    parseJSON  = genericParseJSON  researchTierParseOptions\ninstance KnownNat n => ToJSON (ResearchTier n) where\n    toJSON     = genericToJSON     researchTierParseOptions\n    toEncoding = genericToEncoding researchTierParseOptions\ninstance FromJSON SomeResearchTier where\n    parseJSON = withObject \"ResearchTier\" $ \\v -> do\n      u <- v .: \"unlock\"\n      t <- v .: \"techs\"\n      SV.withSized t $ \\tV ->\n        return $ sing :=> ResearchTier u tV\ninstance ToJSON SomeResearchTier where\n    toJSON = \\case\n        SNat :=> r -> toJSON r\n    toEncoding = \\case\n        SNat :=> r -> toEncoding r\ninstance FromJSON SomeResearchData where\n    parseJSON = withObject \"ResearchData\" $ \\v -> do\n        res   <- v .: \"common\"\n        epics <- (fmap . fmap) (round @Double) <$> v .: \"epic\"\n        withV res $ \\resV ->\n          some (withProd (dsumSome . getI) resV) $ \\(_ :&: (unzipP->(resS :&: resP))) ->\n            SV.withSized epics   $ \\sizedV ->\n              return (STuple2 (fromTC @(Prod Sing) resS) SNat :=> Uncur (ResearchData resP sizedV))\ninstance ToJSON SomeResearchData where\n    toJSON = \\case\n        _ :=> Uncur r -> toJSON r\n    toEncoding = \\case\n        _ :=> Uncur r -> toEncoding r\ninstance (SingI tiers, KnownNat epic) => FromJSON (ResearchData tiers epic) where\n    parseJSON = withObject \"ResearchData\" $ \\v -> do\n        res   <- v .: \"common\"\n        resV  <- go sing res\n        epics <- (fmap . fmap) (round @Double) <$> v .: \"epic\"\n        epicsV <- case SV.toSized epics of\n          Nothing -> fail \"Bad number of items in list.\"\n          Just eV -> return eV\n        return $ ResearchData resV epicsV\n      where\n        go :: Sing ts -> [Value] -> Parser (Prod ResearchTier ts)\n        go = \\case\n          SNil -> \\case\n            []  -> return \u00d8\n            _:_ -> fail \"Too many items in list\"\n          SNat `SCons` ss -> \\case\n            []   -> fail \"Too few items in list\"\n            x:xs -> (:<) <$> parseJSON x <*> go ss xs\n\ninstance ToJSON (ResearchData tiers epic) where\n    toJSON ResearchData{..} = object\n        [ \"common\" .= TCP.toList (\\ResearchTier{..} ->\n                          object [ \"unlock\" .= _rtUnlock\n                                 , \"techs\"  .= SV.fromSized _rtTechs\n                                 ]\n                        ) _rdCommon\n        , \"epic\"   .= SV.fromSized _rdEpic\n        ]\n    toEncoding ResearchData{..} = pairs . mconcat $\n        [ \"common\" .= TCP.toList (\\ResearchTier{..} ->\n                          object [ \"unlock\" .= _rtUnlock\n                                 , \"techs\"  .= SV.fromSized _rtTechs\n                                 ]\n                        ) _rdCommon\n        , \"epic\"   .= SV.fromSized _rdEpic\n        ]\n\ninstance (SingI tiers, KnownNat epic) => FromJSON (ResearchStatus tiers epic) where\n    parseJSON = withObject \"ResearchStatus\" $ \\v -> do\n        res   <- v .: \"common\"\n        resV  <- go sing res\n        epics <- v .: \"epic\"\n        epicsV <- case SV.toSized epics of\n          Nothing -> fail \"Bad number of items in list.\"\n          Just eV -> return eV\n        return $ ResearchStatus resV epicsV\n      where\n        go :: Sing ts -> [Value] -> Parser (Prod (Flip SV.Vector Natural) ts)\n        go = \\case\n          SNil -> \\case\n            []  -> return \u00d8\n            _:_ -> fail \"Too many items in list\"\n          SNat `SCons` ss -> \\case\n            []   -> fail \"Too few items in list\"\n            x:xs -> (:<) <$> parseJSON x <*> go ss xs\ninstance ToJSON (ResearchStatus tiers epic) where\n    toJSON ResearchStatus{..} = object\n        [ \"common\" .= TCP.toList (SV.fromSized . getFlip) _rsCommon\n        , \"epic\"   .= SV.fromSized _rsEpic\n        ]\n    toEncoding ResearchStatus{..} = pairs . mconcat $\n        [ \"common\" .= TCP.toList (SV.fromSized . getFlip) _rsCommon\n        , \"epic\"   .= SV.fromSized _rsEpic\n        ]\ninstance FromJSON SomeResearchStatus where\n    parseJSON = withObject \"ResearchStatus\" $ \\v -> do\n        res   <- v .: \"common\"\n        epics <- v .: \"epic\"\n        withV res $ \\resV ->\n          some (withProd (go . getI) resV) $ \\(_ :&: (unzipP->(resS :&: resP))) ->\n            SV.withSized epics   $ \\sizedV ->\n              return (STuple2 (fromTC resS) SNat :=> Uncur (ResearchStatus resP sizedV))\n      where\n        go :: V.Vector Natural -> Some (Sing :&: Flip SV.Vector Natural)\n        go v = SV.withSized v $ \\u -> Some (SNat :&: Flip u)\ninstance ToJSON SomeResearchStatus where\n    toJSON = \\case\n        _ :=> Uncur r -> toJSON r\n    toEncoding = \\case\n        _ :=> Uncur r -> toEncoding r\n\n-- | Scales a bonus amount by a \"level\".\nscaleAmount :: Natural -> BonusAmount -> BonusAmount\nscaleAmount n = \\case\n    BAIncrement  i -> BAIncrement  (fromIntegral n * i)\n    BAPercent    p -> BAPercent    (fromIntegral n * p)\n    BAMultiplier r -> BAMultiplier (r ^ n)\n\n-- | Tells whether or not a bonus amount creates any actual effect.\nhasEffect :: BonusAmount -> Bool\nhasEffect = \\case\n    BAIncrement  i -> i /= 0\n    BAPercent    p -> p /= 0\n    BAMultiplier r -> r /= 1\n\n-- | A \"smart constructor\" that clears bonuses with no effect.\nbonuses :: M.Map BonusType [BonusAmount] -> Bonuses\nbonuses = Bonuses . M.filter (not . null) . fmap (filter hasEffect)\n\n-- | Apply a list of bonuses (from left to right) to a value.\nbonusEffect :: Fractional a => [BonusAmount] -> a -> a\nbonusEffect = flip . foldl' $ \\e -> \\case\n    BAIncrement  i -> e + realToFrac i\n    BAPercent    p -> e * (1 + realToFrac p / 100)\n    BAMultiplier r -> e * realToFrac r\n\n-- | Iso on a value under a list of bonuses (from left to right).\nbonusing :: (Fractional a, Eq a) => [BonusAmount] -> Iso' a a\nbonusing = flip foldl' id $ \\e -> \\case\n             BAIncrement i  -> e . adding (realToFrac i)\n             BAPercent   p  -> e . multiplying (1 + realToFrac p / 100)\n             BAMultiplier r -> e . multiplying (realToFrac r)\n\n-- | Iso on a value under the bonuses of a given bonus type.\nbonusingFor\n    :: (Fractional a, Eq a)\n    => Bonuses\n    -> BonusType\n    -> Iso' a a\nbonusingFor bs bt = case M.lookup bt (_bMap bs) of\n                      Nothing -> id\n                      Just bl -> bonusing bl\n\n-- | Apply bonuses for a given type on a value.\nbonusEffectFor :: Fractional a => Bonuses -> BonusType -> a -> a\nbonusEffectFor bs bt = maybe id bonusEffect $ M.lookup bt (_bMap bs)\n\n-- | No bonuses\nemptyBonuses :: Bonuses\nemptyBonuses = Bonuses M.empty\n\n-- | Maximum level for a given research.\nmaxLevel :: Research a -> Natural\nmaxLevel = fromIntegral . V.length . _rCosts\n\n-- | Empty status (no research).\nemptyResearchStatus :: ResearchData tiers epic -> ResearchStatus tiers epic\nemptyResearchStatus ResearchData{..} =\n    ResearchStatus (map1 clear _rdCommon) (0 <$ _rdEpic)\n  where\n    clear :: ResearchTier a -> Flip SV.Vector Natural a\n    clear = Flip . set mapped 0 . view rtTechs\n\n-- | Zips together all research data and research statuses into an\n-- accumulator.\nfoldResearch\n    :: Monoid b\n    => (Either (Research Bock) (Research GoldenEgg) -> Natural -> b)\n    -> ResearchData tiers epic\n    -> ResearchStatus tiers epic\n    -> b\nfoldResearch f ResearchData{..} ResearchStatus{..} = mconcat\n    [ foldMap1 (\\case d :&: Flip s -> fold $ SV.zipWith (f . Left) (_rtTechs d) s\n               )\n        (zipP (_rdCommon :&: _rsCommon))\n    , fold $ SV.zipWith (f . Right) _rdEpic _rsEpic\n    ]\n\n-- | Bonuses from a given 'Research' at a given level.  Assumes no \"maximum\n-- level\".\nresearchBonuses :: Research a -> Natural -> Bonuses\nresearchBonuses _ 0 = Bonuses M.empty\nresearchBonuses r l = _rBaseBonuses r & _Bonuses . mapped . mapped %~ scaleAmount l\n\n-- | Total bonuses from a given 'ResearchStatus'.\ntotalBonuses :: ResearchData tiers epic -> ResearchStatus tiers epic -> Bonuses\ntotalBonuses = foldResearch (either researchBonuses researchBonuses)\n\n-- | How many common techs have been researched?\n--\n-- Used for opening tiers.\nresearchCount :: ResearchStatus tiers epic -> Natural\nresearchCount = sumOf $ rsCommon . liftTraversal (_Flip . folded)\n\nlegalTiers\n    :: forall tiers epic. ()\n    => ResearchData tiers epic\n    -> ResearchStatus tiers epic\n    -> Prod (C Bool) tiers\nlegalTiers rd rs = rd ^. rdCommon . to (map1 go)\n  where\n    tot = researchCount rs\n    go  :: ResearchTier a\n        -> C Bool a\n    go = view $ rtUnlock . to (>= tot) . _Unwrapped\n\ndata ResearchError = REMaxedOut\n                   | RELocked\n  deriving (Show, Eq, Ord)\n\nmakePrisms ''ResearchError\n\n-- | Purchase research at a given index, incrementing the counter in the\n-- 'ResearchStatus'.  Returns 'Nothing' if research is already maxed out.\npurchaseResearch\n    :: forall tiers epic a. (KnownNat epic, SingI tiers)\n    => ResearchData tiers epic\n    -> ResearchIx tiers epic a\n    -> ResearchStatus tiers epic\n    -> Either ResearchError (a, ResearchStatus tiers epic)\npurchaseResearch rd i rs0 = pp . getComp . researchIxStatusLegal rd i (Comp . go) $ rs0\n  where\n    bs = totalBonuses rd rs0\n    pp :: Maybe (First a, ResearchStatus tiers epic)\n        -> Either ResearchError (a, ResearchStatus tiers epic)\n    pp Nothing                     = Left REMaxedOut\n    pp (Just (First Nothing , _ )) = Left RELocked\n    pp (Just (First (Just c), rs)) = case i of\n        RICommon _ -> Right (c ^. bonusingFor bs BTResearchCosts, rs)\n        RIEpic   _ -> Right (c, rs)\n    go :: Natural -> Maybe (First a, Natural)\n    go currLevel = first (First . Just) <$>\n      rd ^? researchIxData i\n          . rCosts\n          . ix (fromIntegral currLevel)\n          . to ((, currLevel + 1) . fromMaybe (0 \\\\ researchIxNum i))\n\n-- | Get a 'Num' instance from a 'ResearchIx'.\nresearchIxNum :: ResearchIx tiers epic a -> Wit (Num a)\nresearchIxNum = \\case\n    RICommon _ -> Wit\n    RIEpic   _ -> Wit\n\n-- | A lens into a 'ResearchData', given the appropriate index.\nresearchIxData\n    :: (KnownNat epic, SingI tiers)\n    => ResearchIx tiers epic a\n    -> Lens' (ResearchData tiers epic) (Research a)\nresearchIxData = \\case\n    RICommon i -> \\f ->\n      let g :: forall a. _ a -> _ (_ a)\n          g x@(slot :&: (_ :&: SNat)) = (_2 . _1 . rtTechs . ixSV slot) f x\n      in  rdCommon $ \\rs -> map1 fanFst . fanSnd\n            <$> sumProd g (i :&: zipP (rs :&: toTC sing))\n    RIEpic i   -> rdEpic . ixSV i\n\n-- | A lens into a 'ResearchStatus', given the appropriate index.\nresearchIxStatus\n    :: (KnownNat epic, SingI tiers)\n    => ResearchIx tiers epic a\n    -> Lens' (ResearchStatus tiers epic) Natural\nresearchIxStatus = \\case\n    RICommon i -> \\f ->\n      let g :: forall a. _ a -> _ (_ a)\n          g x@(slot :&: (_ :&: SNat)) = (_2 . _1 . _Flip . ixSV slot) f x\n      in  rsCommon $ \\rs -> map1 fanFst . fanSnd\n            <$> sumProd g (i :&: zipP (rs :&: toTC sing))\n    RIEpic i   -> rsEpic . ixSV i\n\n-- | Lens into both the research data and research status common slots\n-- together.\nrdrsCommon\n    :: Lens' ((Uncur ResearchData :&: Uncur ResearchStatus) (tiers # epic))\n             (Prod (ResearchTier :&: Flip SV.Vector Natural) tiers)\nrdrsCommon f (Uncur rd :&: Uncur rs) =\n    f (zipP (_rdCommon rd :&: _rsCommon rs)) <&> \\(unzipP->(rdc :&: rsc)) ->\n      Uncur (rd & rdCommon .~ rdc) :&: Uncur (rs & rsCommon .~ rsc)\n\n-- | Lens into both the research data and research status epic slots\n-- together.\nrdrsEpic\n    :: KnownNat epic\n    => Lens' ((Uncur ResearchData :&: Uncur ResearchStatus) (tiers # epic))\n             (SV.Vector epic (Research GoldenEgg, Natural))\nrdrsEpic f (Uncur rd :&: Uncur rs) =\n    f (liftA2 (,) (_rdEpic rd) (_rsEpic rs)) <&> \\rdrs ->\n      Uncur (rd & rdEpic .~ fmap fst rdrs) :&: Uncur (rs & rsEpic .~ fmap snd rdrs)\n\n-- | Lens into both a ResearchData and ResearchStatus together, from\n-- a given index.\nresearchIx\n    :: (SingI tiers, KnownNat epic)\n    => ResearchIx tiers epic a\n    -> Lens' ((Uncur ResearchData :&: Uncur ResearchStatus) (tiers # epic))\n             (Research a, Natural)\nresearchIx = \\case\n    RICommon i -> \\f ->\n      let g :: forall a. _ a\n            -> _ (_ a)\n          g (slot :&: ((c :&: Flip e) :&: SNat)) =\n              f (SV.index (_rtTechs c) slot, SV.index e slot) <&> \\(d, s) ->\n                let c' = c & rtTechs . ixSV slot .~ d\n                    e' = e & ixSV slot .~ s\n                in  slot :&: ((c' :&: Flip e') :&: SNat)\n      in  rdrsCommon $ \\rdrs ->\n            map1 fanFst . fanSnd <$> sumProd g (i :&: zipP (rdrs :&: toTC sing))\n    RIEpic i -> rdrsEpic . ixSV i\n\nwithSomeResearch\n    :: DSum Sing (Uncur res)\n    -> (forall tiers epic. (KnownNat epic, SingI tiers) => res tiers epic -> r)\n    -> r\nwithSomeResearch = \\case\n    STuple2 sTs SNat :=> Uncur r -> \\f -> withSingI sTs $ f r\n\n-- | Traversal into a given index of a 'ResearchStatus' if the item is in\n-- a legal tier.\n--\n-- Only a legal traversal if the mapping function doesn't change the legal\n-- status.\nresearchIxStatusLegal\n    :: (SingI tiers, KnownNat epic)\n    => ResearchData tiers epic\n    -> ResearchIx tiers epic a\n    -> Traversal' (ResearchStatus tiers epic) Natural\nresearchIxStatusLegal rd = \\case\n    RICommon i -> \\f rs0 -> getUncur . fanSnd <$>\n      let totCount = researchCount rs0\n          g :: forall a. _ a -> _ (_ a)\n          g x@(slot :&: ((rt :&: _) :&: SNat))\n            | _rtUnlock rt <= totCount = (_2 . _1 . _2 . _Flip . ixSV slot) f x\n            | otherwise                = pure x\n      in  (Uncur rd :&: Uncur rs0) & rdrsCommon %%~ \\rtrs ->\n            map1 fanFst . fanSnd <$> sumProd g (i :&: zipP (rtrs :&: toTC sing))\n    RIEpic i   -> rsEpic . ixSV i\n\n-- | All 'ResearchIx' into common researches.\nresearchIxesCommon\n    :: SingI tiers\n    => Prod (Flip SV.Vector (ResearchIx tiers epic Bock)) tiers\nresearchIxesCommon = go sing\n  where\n    go :: Sing ts -> Prod (Flip SV.Vector (ResearchIx ts epic Bock)) ts\n    go = \\case\n      SNil         -> \u00d8\n      SNat `SCons` ss ->\n        let rest = map1 (over (_Flip . mapped . _RICommon) InR) (go ss)\n        in  Flip (SV.generate (RICommon . InL)) :< rest\n\n-- | All 'ResearchIx' into epic researches.\nresearchIxesEpic\n    :: KnownNat epic\n    => SV.Vector epic (ResearchIx tiers epic GoldenEgg)\nresearchIxesEpic = SV.generate RIEpic\n\n-- | All legal 'ResearchIx' for common research.\nlegalResearchIxesCommon\n    :: forall tiers epic. SingI tiers\n    => ResearchData tiers epic\n    -> ResearchStatus tiers epic\n    -> Prod (Flip SV.Vector (Either ResearchError (ResearchIx tiers epic Bock))) tiers\nlegalResearchIxesCommon rd rs =\n    imap1 (\\i -> Flip . go i) (zipP (zipP (_rdCommon rd :&: _rsCommon rs) :&: toTC sing))\n  where\n    totCount = researchCount rs\n    go  :: forall t. ()\n        => Index tiers t\n        -> ((ResearchTier :&: Flip SV.Vector Natural) :&: Sing) t\n        -> SV.Vector t (Either ResearchError (ResearchIx tiers epic Bock))\n    go i ((rt :&: Flip c) :&: SNat)\n      | rt ^. rtUnlock > totCount = pure (Left RELocked)\n      | otherwise                 =\n          let mkIx\n                  :: Finite t\n                  -> Research Bock\n                  -> Natural\n                  -> Either ResearchError (ResearchIx tiers epic Bock)\n              mkIx j r n\n                | n < maxLevel r = Right . RICommon . someSum $ Some (i :&: j)\n                | otherwise      = Left REMaxedOut\n          in  SV.izipWith mkIx (rt ^. rtTechs) c\n\n-- | All legal 'ResearchIx' for epic research.\n--\n-- 'Nothing' implies research is maxed-out.\nlegalResearchIxesEpic\n    :: forall tiers epic. KnownNat epic\n    => ResearchData tiers epic\n    -> ResearchStatus tiers epic\n    -> (SV.Vector epic :.: Maybe) (ResearchIx tiers epic GoldenEgg)\nlegalResearchIxesEpic rd rs = Comp $ SV.izipWith go (_rdEpic rd) (_rsEpic rs)\n  where\n    go  :: Finite epic\n        -> Research GoldenEgg\n        -> Natural\n        -> Maybe (ResearchIx tiers epic GoldenEgg)\n    go i r n\n      | n < maxLevel r = Just . RIEpic $ i\n      | otherwise      = Nothing\n\n-- | All legal common researches.\nlegalResearchesCommon\n    :: forall tiers epic. SingI tiers\n    => ResearchData tiers epic\n    -> ResearchStatus tiers epic\n    -> Prod (Flip SV.Vector (Either ResearchError Bock)) tiers\nlegalResearchesCommon rd rs =\n    map1 (Flip . go) (zipP (zipP (_rdCommon rd :&: _rsCommon rs) :&: toTC sing))\n  where\n    bs       = totalBonuses rd rs\n    totCount = researchCount rs\n    go  :: forall t. ()\n        => ((ResearchTier :&: Flip SV.Vector Natural) :&: Sing) t\n        -> SV.Vector t (Either ResearchError Bock)\n    go ((rt :&: Flip c) :&: SNat)\n      | rt ^. rtUnlock > totCount = pure (Left RELocked)\n      | otherwise                 = do\n          r         <- rt ^. rtTechs\n          currLevel <- c\n          pure $ case r ^? rCosts . ix (fromIntegral currLevel) of\n            Nothing -> Left REMaxedOut\n            Just b  -> Right $ fromMaybe 0 b ^. bonusingFor bs BTResearchCosts\n\n-- | All legal epic researches.\n--\n-- 'Nothing' implies research is maxed-out.\nlegalResearchesEpic\n    :: forall tiers epic. KnownNat epic\n    => ResearchData tiers epic\n    -> ResearchStatus tiers epic\n    -> (SV.Vector epic :.: Maybe) GoldenEgg\nlegalResearchesEpic rd rs = Comp $ do\n    r         <- _rdEpic rd\n    currLevel <- _rsEpic rs\n    pure $ fromMaybe 0 <$> r ^? rCosts . ix (fromIntegral currLevel)\n\n", "meta": {"hexsha": "cab595dd697137db50e60e2ad3d16c6dbd24bd00", "size": 28447, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Egg/Research.hs", "max_stars_repo_name": "mstksg/eggvisor", "max_stars_repo_head_hexsha": "9bca62aef60de85e0d30fccf7b2926962979c352", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-31T17:40:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:53:49.000Z", "max_issues_repo_path": "src/Egg/Research.hs", "max_issues_repo_name": "mstksg/eggvisor", "max_issues_repo_head_hexsha": "9bca62aef60de85e0d30fccf7b2926962979c352", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Egg/Research.hs", "max_forks_repo_name": "mstksg/eggvisor", "max_forks_repo_head_hexsha": "9bca62aef60de85e0d30fccf7b2926962979c352", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-18T14:06:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-18T14:06:45.000Z", "avg_line_length": 37.4795783926, "max_line_length": 99, "alphanum_fraction": 0.5901149506, "num_tokens": 7704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3040416749665474, "lm_q1q2_score": 0.19147772226126933}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE NamedFieldPuns    #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RankNTypes        #-}\n{-# LANGUAGE RecordWildCards   #-}\n{-# LANGUAGE TemplateHaskell   #-}\n{-# LANGUAGE TupleSections     #-}\n\n\nmodule Topical.Text.Tokenizer.TextTiling\n    ( SmoothingParams(..)\n\n    , textTilingTokenizer\n    , suppressSmallBlocks\n    , smooth\n\n    , windows\n    , partition\n    , triples\n    , frequencies\n    , blockComparison\n    , vocabularyIntroduction\n\n    , Sequence(..)\n    , seqNo\n    , seqSpan\n    , seqItems\n    , seqFreqs\n\n    , SeqScore\n    ) where\n\n\nimport           Control.Arrow\nimport           Control.Error\nimport           Control.Lens\n-- import           Data.Foldable       hiding (concat)\nimport           Data.Hashable\nimport qualified Data.HashMap.Strict as M\nimport qualified Data.HashSet        as S\nimport qualified Data.List           as L\nimport qualified Data.List.Split     as Split\nimport           Data.Monoid\nimport           Data.Ord\nimport qualified Data.Text           as T\nimport           Data.Traversable\n-- import qualified Data.Vector         as V\n-- import           Statistics.Sample\n\n-- import           Topical.Text.Types\n\n\ntype Frequency         = Int\n-- type TokenSeqFrequency = (SeqNumber, Frequency)\n\n-- | \"The morpholocially-analyzed token is stored in a table along with\n-- a record of the token-windowSeq number it occurred in, and the number of\n-- times it appeared in the token-sequence.\"\n-- type TokenTable a      = M.HashMap a [TokenSeqFrequency]\n\ntype SeqNumber = Int\n\n-- | A record is also kept of the locations of the paragraph breaks within\n-- the text. Stop words contribute to the computation of the size of the\n-- token windowSeq, but not to the computation of the similarity between\n-- blocks of text.\ntype SeqSpan = (Int, Int)\n\ntype FrequencyTable a = M.HashMap a Frequency\n\ndata Sequence a b = Sequence\n                  { _seqNo    :: !SeqNumber\n                  , _seqSpan  :: !SeqSpan\n                  , _seqItems :: ![a]\n                  , _seqFreqs :: !(FrequencyTable b)\n                  } deriving (Eq)\nmakeLenses ''Sequence\n\ninstance Show (Sequence T.Text b) where\n    show Sequence{..} =\n        mconcat [ \"Sequence #\"\n                , show _seqNo\n                , \": \"\n                , T.unpack (T.unwords _seqItems)\n                ]\n\ntype TokenSequence a = Sequence a a\ntype BlockSequence a = Sequence (TokenSequence a) a\n\ntype SeqScore a b = (TokenSequence a, b)\n\ndata SmoothingParams  = Smoothing Int    -- ^ Number of rounds of smoothing\n                                  Int    -- ^ Smoothing window size\n\ntype ScoringFunction a =\n    TokenSeqSize -> BlockSize -> [TokenSequence a] -> [SeqScore a Double]\ntype CountFunction a b = (Hashable b, Eq b) => [a] -> FrequencyTable b\n\ntype TokenSeqSize = Int\ntype BlockSize    = Int\n\n-- | The basic processing flow:\n-- boundary identification . lexical score determination . tokenization\ntextTilingTokenizer :: (Hashable a, Eq a, Show a)\n                    => TokenSeqSize\n                    -- ^ The token windowSeq size parameter (/w/). 20 is often\n                    -- a good default value.\n                    -> BlockSize\n                    -- ^ The number of token sequences to group together.\n                    -- This is the average paragraph length (in token\n                    -- sequences) (/blocksize/). 6 often works well.\n                    -> ScoringFunction a\n                    -- ^ This either uses block comparison to look at\n                    -- shared vocabulary or vocabulary introduction to base\n                    -- it on the number of new words are found in the\n                    -- second window. Either way, larger output values\n                    -- should indicate a more likely change of topic.\n                    -> SmoothingParams\n                    -> [a]\n                    -- ^ The input sequence. If this is text, this should\n                    -- be tokenized, case-folded, and stop-words filtered\n                    -- out. Also, affixes and irregular forms normalized\n                    -- should be removed so that it's only the\n                    -- morphological base.\n                    -> [BlockSequence a]\ntextTilingTokenizer w k scoring (Smoothing sWin sIters) =\n      cutOffs\n    . smooth sWin sIters\n    . snd\n    . mapAccumConcat boundary (0, 0, [])\n    . scoring w k\n    . partitionSeq w frequencies\n\ncutOffs :: [SeqScore a (Double, Double)] -> [BlockSequence a]\ncutOffs = undefined\n\n-- The first Double is the raw score. The second is the depth score\n-- actually used to make the boundary determination.\n-- type SeqNode a = SeqScore a (Double, Double)\n\n-- | This takes a list of @SeqScore a (Double, Double)@, sorted by\n-- likelihood of beginning a new section, and returns a tree of descending\n-- likelihoods, but in sequence order.\n-- hangTree :: Show a => [SeqNode a] -> Tree (SeqNode a)\n-- hangTree = unfoldTree hang\n--     where\n--         hang :: Show a\n--                 => [SeqNode a]\n--                     -> (SeqNode a, (Maybe [SeqNode a], Maybe [SeqNode a]))\n--         hang = undefined\n--              . maximumBy (comparing (snd . snd . fst))\n--              . snd\n--              . L.mapAccumL packageNode []\n--              . filter (not . L.null)\n--              . L.tails\n--\n--         packageNode :: Show a\n--                        => [SeqNode a]\n--                            -> [SeqNode a]\n--                            -> ([SeqNode a], (SeqNode a, [[SeqNode a]]))\n--         packageNode ls (s:rs) = (s:ls, (s, [reverse ls, rs]))\n--         packageNode ls []     = (ls,   (undefined, []))\n--         -- It should never reach here, so I'll just plant a bomb.\n--         -- KA-BOOM!\n\nsmooth :: Int -> Int -> [SeqScore a (Double, Double)]\n       -> [SeqScore a (Double, Double)]\nsmooth _      0     sss = sss\nsmooth window iters sss =\n    smooth window (pred iters) $ moveAvgBy window (_2 . _2) sss\n\nmoveAvgBy :: Int       -- ^ The number of items to offset from each side\n                       -- of the center. For instance, for a window of 3,\n                       -- use a value of 1.\n          -> Lens' a Double -> [a] -> [a]\nmoveAvgBy n l xs = zipWith (set l) (moveavg n $ map (^. l) xs) xs\n\nmoveavg :: Int         -- ^ The number of items to offset from each side\n                       -- of the center. For instance, for a window of 3,\n                       -- use a value of 1.\n        -> [Double] -> [Double]\nmoveavg n = go []\n    where\n        go _    []     = []\n        go pref (x:xs) = avg (x : take n pref ++ take n xs) : go (x:pref) xs\n\navg :: [Double] -> Double\navg = uncurry (/) . L.foldl' accum (0, 0)\n    where\n        accum p x = ((+ x) *** succ) p\n\nsuppressSmallBlocks :: Int\n                    -> [SeqScore a (Double, Double)]\n                    -> [SeqScore a (Double, Double)]\nsuppressSmallBlocks minP = sortNo . removeTiny minP . sortScore\n    where\n        removeTiny :: Int\n                   -> [SeqScore a0 (Double, Double)]\n                   -> [SeqScore a0 (Double, Double)]\n        removeTiny _ []     = []\n        removeTiny w (x:xs) =\n            x : sortScore (map (modifyClose w $ x ^. _1 . seqNo) xs)\n        closeTo :: Int -> Int -> SeqScore a1 (Double, Double) -> Bool\n        closeTo w seq1No seq2 = abs (seq1No - (seq2 ^. _1 . seqNo)) <= w\n        modifyClose :: Int\n                    -> Int\n                    -> SeqScore a2 (Double, Double)\n                    -> SeqScore a2 (Double, Double)\n        modifyClose w seq1No seq2 = if closeTo w seq1No seq2\n                                        then seq2 & _2 . _2 .~ 0\n                                        else seq2\n\nsortScore :: [SeqScore a (Double, Double)] -> [SeqScore a (Double, Double)]\nsortScore = L.sortBy (comparing (Down . snd . snd))\n\nsortNo :: [SeqScore a b] -> [SeqScore a b]\nsortNo = L.sortBy (comparing (_seqNo . fst))\n\ntype BoundaryId a = (Double, Double, [Double -> SeqScore a (Double, Double)])\n\nboundary :: BoundaryId a\n         -> SeqScore a Double\n         -> (BoundaryId a, [SeqScore a (Double, Double)])\nboundary (leftS, lastS, pending) (ts, s)\n    | lastS <= s = ((leftS', s, nextf:pending), [])\n    | otherwise  = ((s, s, []), reverse (map ($ lastS) (nextf:pending)))\n    where\n        leftS'  = max leftS s\n        nextf r = (ts, (s, (leftS' - s) + (r - s)))\n\n-- | This converts a two-item list into a tuple pair.\ntoPair :: [a] -> Maybe (a, a)\ntoPair [a, b] = Just (a, b)\ntoPair _      = Nothing\n\n-- toTriples :: [a] -> Maybe (a, a, a)\n-- toTriples [a, b, c] = Just (a, b, c)\n-- toTriples _         = Nothing\n\nmapAccumConcat :: (a -> b -> (a, [c])) -> a -> [b] -> (a, [c])\nmapAccumConcat f s = fmap concat . mapAccumL f s\n\n-- TODO: I think this should be a comonad, but right now I just want to get\n-- it written.\n-- mapAccumContext :: (s -> [x] -> x -> [x] -> (s, [a])) -> s -> [x] -> (s, [a])\n-- mapAccumContext f state = go state []\n--     where\n--         go s _  []     = (s, [])\n--         go s ls (x:xs) = let (s',  as)  = f s ls x xs\n--                              (s'', ass) = go s' (x:ls) xs\n--                          in  (s'', as ++ ass)\n\n-- | The block comparison scoring function. This looks at words in common\n-- between two windows.\n-- TODO: I think we're loosing `bsize` token sequences off the front.\nblockComparison :: (Hashable a, Eq a) => ScoringFunction a\nblockComparison _ _ []      = []\nblockComparison _ bsize tss =\n      uncurry appHead\n    . (floatHead &&& comparePairs)\n    $ windowSeq bsize mergeFrequencies tss\n    where\n        floatHead seqs = (,0.0) <$> seqs ^? i0 . seqItems . i0\n        comparePairs   = map (uncurry blockCompare) . mapMaybe toPair . windows 2\n        appHead mh xs  = maybe xs (:xs) mh\n        i0             = traversed . index 0\n\nblockCompare :: (Hashable a, Eq a)\n             => BlockSequence a -> BlockSequence a -> SeqScore a Double\nblockCompare (Sequence _ _ _ b1) (Sequence _ _ (ts:_) b2) =\n    (ts,) . final . foldMap step $ terms b1 `S.union` terms b2\n    where\n        topf w1 w2     = w1 * w2\n        bottoml w1 _w2 = w1 * w1\n        bottomr _w1 w2 = w2 * w2\n        getFreqs t     = (M.lookupDefault 0 t b1, M.lookupDefault 0 t b2)\n        step           = (   Sum . uncurry topf\n                         &&& Sum . uncurry bottoml\n                         &&& Sum . uncurry bottomr\n                         ) . getFreqs\n        final (Sum t, (Sum bl, Sum br)) =\n            fromIntegral t / sqrt (fromIntegral $ bl * br)\nblockCompare _ _ = undefined\n\n-- | This returns the terms in a frequency table.\nterms :: (Hashable a, Eq a) => FrequencyTable a -> S.HashSet a\nterms = S.fromList . M.keys\n\n-- | The vocabulary introduction scoring function. This looks at how many\n-- words are introduced in the second window.\n-- TODO: What happens to the first item from the first pair in `collapse`?\n-- TODO: Are we looking a token sequence off the front?\nvocabularyIntroduction :: (Hashable a, Eq a) => ScoringFunction a\nvocabularyIntroduction tsSize _ = snd\n                                . mapAccumL accum S.empty\n                                . map (uncurry collapse)\n                                . mapMaybe toPair\n                                . windows 2\n                                . map (id &&& (terms . _seqFreqs))\n    where\n        blockSize :: Double\n        blockSize = fromIntegral tsSize * 2.0\n        collapse (_, t1) (ts, t2) = (ts, t1 `S.union` t2)\n        accum s (ts, block) =\n            let unseen = S.size $ block `S.difference` s\n                s'     = s `S.union` block\n            in  (s', (ts, fromIntegral unseen / blockSize))\n\n-- | This extends @windows@ to create @Sequence@ instances.\nwindowSeq :: (Eq b, Hashable b)\n          => Int -> CountFunction a b -> [a] -> [Sequence a b]\nwindowSeq k = toSeq (windows k)\n\n-- | This extends @partition@ to create @Sequence@ data.\npartitionSeq :: (Eq b, Hashable b)\n             => Int -> CountFunction a b -> [a] -> [Sequence a b]\npartitionSeq k = toSeq (partition k)\n\ntoSeq :: (Eq b, Hashable b)\n      => ([(Int, a)] -> [[(Int, a)]])\n      -> CountFunction a b -> [a] -> [Sequence a b]\ntoSeq breaker counter =\n    mapMaybe (uncurry toSeq') . zip [0..] . breaker . zip [0..]\n    where\n        toSeq' n spanned =\n            let items = map snd spanned\n            in  Sequence n <$> getSpan spanned\n                           <*> pure items\n                           <*> pure (counter items)\n        getSpan []          = Nothing\n        getSpan [(s, _)]    = Just (s, s)\n        getSpan ((s, _):xs) = (s,) . fst <$> lastZ xs\n\n-- | This takes an input windowSeq and divides it into overlapping\n-- subsequences of a given size.\n--\n-- >>> windows 2 [1, 2, 3, 4, 5]\n-- [[1, 2], [2, 3], [3, 4], [4, 5], [5]]\nwindows :: Int      -- ^ The size of the sliding window.\n        -> [a]      -- ^ The input sequence.\n        -> [[a]]    -- ^ The output windowSeq of windows.\nwindows k = filter (not . L.null) . map (take k) . L.tails\n\n-- | This implementation is taken from Data.List.Split.Lens, before it was\n-- removed.\nchunking :: Int -- ^@n@\n         -> Getting (Endo [a]) s a -> Fold s [a]\nchunking s l f = coerce . traverse f . Split.chunksOf s . toListOf l\n{-# INLINE chunking #-}\n\n-- | This takes an input windowSeq and divides it into non-overlapping\n-- partitions of a given size.\n--\n-- >> partition 2 [1, 2, 3, 4, 5]\n-- [[1, 2], [3, 4], [5]]\npartition :: Int    -- ^ The size of the non-overlapping partitions.\n          -> [a]    -- ^ The input windowSeq to partition.\n          -> [[a]]  -- ^ The non-overlapping partitions.\npartition k xs = xs ^.. chunking k each\n\n-- | This takes an input windowSeq and divides it into overlapping chains of\n-- three.\n--\n-- >>> triples [1, 2, 3, 4, 5]\n-- [(1, 2, 3), (2, 3, 4), (3, 4, 5)]\ntriples :: [a] -> [(a, a, a)]\ntriples = mapMaybe triples' . L.tails\n    where\n        triples' (a:b:c:_) = Just (a, b, c)\n        triples' _         = Nothing\n\nfrequencies :: CountFunction a a\nfrequencies xs = M.fromListWith (+) . zip xs $ L.repeat 1\n\nmergeFrequencies :: CountFunction (Sequence a b) b\nmergeFrequencies = foldMap _seqFreqs\n\n-- cosSimilarity :: (Hashable a, Eq a)\n--               => FrequencyTable a -> FrequencyTable a -> Double\n-- cosSimilarity b1 b2 =\n--     finish . foldMap step $ terms b1 `S.union` terms b2\n--     where step k = let w1 = M.lookupDefault 0 k b1\n--                        w2 = M.lookupDefault 0 k b2\n--                     in (Sum (w1 * w2), Sum (w1 * w1), Sum (w2 * w2))\n--           finish (Sum a, Sum b, Sum c) =\n--               fromIntegral a / sqrt (fromIntegral b * fromIntegral c)\n\n-- | This calculates all boundaries as being places where the depth score\n-- is greater than the function below (mean minus half the standard\n-- deviation).\n--\n-- If I need better performance, I can use\n-- http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm\n\n-- boundaries :: [Double] -- ^ The cutoff scores between each paragraph block.\n--            -> [Int]    -- ^ A list of the paragraph indexes that are boundaries.\n-- boundaries depths = undefined $ mean depths' - (fastStdDev depths' / 2.0)\n--     where depths' = V.fromList depths\n\n\n-- Stuff from Main for this:\n-- main :: IO ()\n-- main = do\n--     (stopfile:files) <- getArgs\n--\n--     stoplist <- S.fromList . tokenize <$> TIO.readFile stopfile\n--\n--     forM_ files $ \\filename -> do\n--         putStrLn filename\n--\n--         tokens <-  filter (not . (`S.member` stoplist)) . tokenize\n--                <$> TIO.readFile filename\n--         putStrLn $ \"Token count = \" ++ show (length tokens)\n--\n--         let tiles = map _seqItems\n--                   $ textTilingTokenizer 20 6 blockComparison (Smoothing 1 2) tokens\n--         putStrLn $ \"Tile count  = \" ++ show (length tiles)\n--\n--         forM_ tiles $ TIO.putStr\n--                     . (<> \"\\n\\n\")\n--                     . T.intercalate \"\\n\\n\"\n--                     . map ((<> \".\") . T.intercalate \" \" . _seqItems)\n--\n-- {-\n--  -         chart tiles\n--  -\n--  -         forM_ tiles $ \\(Sequence{..}, (raw, score)) ->\n--  -             putStrLn $ L.intercalate \",\" [ show _seqNo\n--  -                                          , show (fst _seqSpan)\n--  -                                          , show (snd _seqSpan)\n--  -                                          , show raw\n--  -                                          , show score\n--  -                                          , unwords (map T.unpack _seqItems)\n--  -                                          ]\n--  -}\n--\n-- chart :: [SeqScore T.Text (Double, Double)] -> IO ()\n-- chart seqs = toFile def \"tiles.png\" $ do\n--     layout_title .= \"TextTiling scores\"\n--     -- layout_y_axis . laxis_override .= axisGridHide\n--     -- plot $ line \"raw\"   [map (fst . _seqSpan *** fst) seqs]\n--     plot $ line \"score\" [map (fst . _seqSpan *** snd) seqs]\n--\n-- {-\n--  - toParagraphs :: Int\n--  -              -> Tree (SeqScore T.Text (Double, Double))\n--  -              -> [[SeqScore T.Text (Double, Double)]]\n--  - toParagraphs 0 tree = [L.sortBy (comparing (_seqNo . fst)) $ flatten tree]\n--  - toParagraphs n (Node root forest) = [sortp pre, root : sortp post]\n--  -     where\n--  -         rootNo      = root ^. _1 . seqNo\n--  -         (pre, post) = L.break ((< rootNo) . _seqNo . fst . head . head)\n--  -                     $ map (toParagraphs (n - 1)) forest\n--  -         sortp       = L.sortBy (comparing (_seqNo . fst . _))\n--  -}\n--\n-- showp :: [SeqScore T.Text (Double, Double)] -> String\n-- showp = L.intercalate \". \" . map (unwords . map T.unpack . _seqItems . fst)\n--\n-- tshow :: Show a => a -> T.Text\n-- tshow = T.pack . show\n--\n-- word :: Parser T.Text\n-- word = T.pack <$> many1 (satisfy isAlphaNum)\n--\n-- tokenize :: T.Text -> [T.Text]\n-- tokenize = map T.toLower . parserTokenizer word\n", "meta": {"hexsha": "a1f6b0959e1c49da6367136bebe54f73aed97ce2", "size": 17804, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Topical/Text/Tokenizer/TextTiling.hs", "max_stars_repo_name": "erochest/topical", "max_stars_repo_head_hexsha": "d2b2e7657d64f343e88790312c8295ab2fcec18b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Topical/Text/Tokenizer/TextTiling.hs", "max_issues_repo_name": "erochest/topical", "max_issues_repo_head_hexsha": "d2b2e7657d64f343e88790312c8295ab2fcec18b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Topical/Text/Tokenizer/TextTiling.hs", "max_forks_repo_name": "erochest/topical", "max_forks_repo_head_hexsha": "d2b2e7657d64f343e88790312c8295ab2fcec18b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0427350427, "max_line_length": 86, "alphanum_fraction": 0.5408335206, "num_tokens": 4775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.19131846660970886}}
{"text": "{-# LANGUAGE GADTs #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE DeriveFunctor #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE RecursiveDo #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE FunctionalDependencies #-}\n\nmodule Dynamical.Sim.Internal where\n\nimport Control.Applicative\nimport Control.DeepSeq (force, NFData(..))\nimport Control.Monad\nimport Control.Monad.Fix (MonadFix(mfix))\nimport Control.Monad.State (StateT, State, get, put, runState, modify, execState, evalState)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Writer (Writer, tell, WriterT, runWriterT)\nimport Control.Parallel (pseq)\nimport qualified Control.Parallel.Strategies as Par\nimport Data.Complex (Complex((:+)))\nimport Data.Default.Class (Default(def))\nimport Data.Fixed (Fixed, mod')\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntSet (IntSet)\nimport qualified Data.IntSet as Set\nimport Data.List\nimport Data.Map (Map)\nimport qualified Data.Map as Map\nimport Data.Maybe\nimport Data.Monoid (Monoid(), Any(Any), (<>), mempty, mappend)\nimport Data.Proxy (Proxy(Proxy))\nimport Data.Scientific (Scientific)\nimport Data.StableMemo (memo)\nimport Data.Time (getCurrentTime, diffUTCTime, UTCTime)\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Generic.Mutable as GM\nimport qualified Data.Vector.Mutable as VM\nimport qualified Data.Vector.Unboxed as UV\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport qualified Debug.Trace as Dbg\nimport GHC.Generics (Generic)\nimport qualified GHC.Prim as Prim\nimport GHC.TypeLits (Symbol, symbolVal, KnownSymbol)\nimport qualified Graphics.Rendering.Chart.Backend.Cairo as Chart\nimport qualified Graphics.Rendering.Chart.Easy as Chart\nimport Linear (V1(..), V2(..), angle, V3(..), V4(..), norm, _x, _y,_z,_w, qd,Additive(..),signorm,(*^),(^/), perp)\nimport System.IO.Unsafe (unsafePerformIO, unsafeInterleaveIO)\nimport System.Mem.StableName (hashStableName,eqStableName,StableName,makeStableName)\nimport Text.Printf (printf, PrintfArg)\nimport Unsafe.Coerce (unsafeCoerce)\n\n-------------------------------------------------------------------\n-- Signal\n-------------------------------------------------------------------\n\n-- | A `Signal t a` represents a time varying value of type `a`, where\n-- time is measured using a `t`.\ndata Signal t a where\n    SPure   :: a -> Signal t a\n    SAp     :: Signal t (a -> b) -> Signal t a -> Signal t b\n    SAdd    :: Num a => Signal t a -> Signal t a -> Signal t a\n    SMul    :: Num a => Signal t a -> Signal t a -> Signal t a\n    SDiv    :: Fractional a => Signal t a -> Signal t a -> Signal t a\n    SMap    :: (a -> b) -> Signal t a -> Signal t b\n    SInt    :: Splat t a => Int -> (a -> b) -> Signal t b\n    SFn     :: Int -> (t -> a) -> Signal t a\n    SSwitch :: Signal t a -> Event t (Sim t (Signal t a)) -> Signal t a\n    SShare  :: Signal t a -> Signal t a\n\ninstance Monoid a => Monoid (Signal t a) where\n    mempty = pure mempty\n    mappend = liftA2 mappend\n\ninstance Functor (Signal t) where\n    fmap f (SMap g s) = SMap (f . g) s\n    fmap f (SInt i g) = SInt i (f . g)\n    fmap f (SPure a) = SPure (f a)\n    -- fmap f (SAp g a) = SAp (fmap (f.) g) a\n    fmap f (SFn i g) = SFn i (f . g)\n    -- fmap f (SSwitch s e) = SSwitch (fmap f s) (fmap (fmap (fmap f)) e)\n    fmap f s = SMap f s\n\ninstance Applicative (Signal t) where\n    pure = SPure\n    (SPure f) <*> (SPure a) = pure (f a)\n    (SPure f) <*> s = fmap f s\n    a <*> b = SAp a b\n\ndbgSig :: Signal t a -> String\ndbgSig (SPure _) = \"SPure\"\ndbgSig (SAp a b) = \"SAp (\" ++ dbgSig a ++ \") (\" ++ dbgSig b ++ \")\"\ndbgSig (SMap _ s) = \"SMap (\" ++ dbgSig s ++ \")\"\ndbgSig (SInt i _) = \"SInt \" ++ show i\ndbgSig (SFn i _) = \"SFn \" ++ show i\ndbgSig (SSwitch s e) = \"SSwitch (\" ++ dbgSig s ++ \")\"\ndbgSig (SShare s) = \"SShare (\" ++ dbgSig s ++ \")\"\ndbgSig (SAdd a b) = \"SAdd (\" ++ dbgSig a ++ \") (\" ++ dbgSig b ++ \")\"\ndbgSig (SDiv a b) = \"SDiv (\" ++ dbgSig a ++ \") (\" ++ dbgSig b ++ \")\"\ndbgSig (SMul a b) = \"SMul (\" ++ dbgSig a ++ \") (\" ++ dbgSig b ++ \")\"\n\ninstance Num a => Num (Signal t a) where\n    fromInteger = pure . fromInteger\n    (SPure a) + (SPure b) = pure $ a + b\n    a + b = SAdd a b\n    (SPure a) * (SPure b) = pure $ a * b\n    a * b = SMul a b\n    abs = fmap abs\n    signum = fmap signum\n    negate = fmap negate\n\ninstance Fractional a => Fractional (Signal t a) where\n    (SPure a) / (SPure b) = pure $ a / b\n    a / b = SDiv a b\n    recip = fmap recip\n    fromRational = pure . fromRational\n\ninstance Floating a => Floating (Signal t a) where\n    pi = pure pi\n    exp = fmap exp\n    log = fmap log\n    sqrt = fmap sqrt\n    (**) = liftA2 (**)\n    logBase = liftA2 (**)\n    sin = fmap sin\n    cos = fmap cos\n    tan = fmap tan\n    asin = fmap asin\n    acos = fmap acos\n    atan = fmap atan\n    sinh = fmap sinh\n    cosh = fmap cosh\n    tanh = fmap tanh\n    asinh = fmap asinh\n    acosh = fmap acosh\n    atanh = fmap atanh\n\n-------------------------------------------------------------------\n-- Event\n-------------------------------------------------------------------\n\n-- | An `Event t a` represents a series of instantaneous events.\ndata Event t a where\n    ERoot  :: (Num a, Ord a) => Signal t a -> Event t ()\n    ETag   :: Event t a -> Signal t b -> Event t (a,b)\n    EMap   :: (a -> b) -> Event t a -> Event t b\n\nevalEvent :: Time t => Network t o -> Event t a -> a\nevalEvent n (ERoot s) = ()\nevalEvent n (EMap f e) = f $ evalEvent n e\nevalEvent n (ETag e s) = (evalEvent n e, evalSignal n s)\n\ninstance Functor (Event t) where\n    fmap = EMap\n\n-------------------------------------------------------------------\n-- Sim\n-------------------------------------------------------------------\n\n-- | The `Sim t` monad is used for constructing certain `Signal` values.\nnewtype Sim t a = Sim {unSim :: forall o. State (Network t o) a}\n\ninstance Num a => Num (Sim t a) where\n    fromInteger = pure . fromInteger\n    (+) = liftA2 (+)\n    (*) = liftA2 (*)\n    abs = fmap abs\n    signum = fmap signum\n    negate = fmap negate\n\n\ninstance Functor (Sim t) where\n    fmap f (Sim s) = Sim (fmap f s)\n\ninstance Applicative (Sim t) where\n    pure a = Sim (pure a)\n    (Sim f) <*> (Sim a) = Sim (f <*> a)\n\ninstance Monad (Sim t) where\n    (Sim a) >>= f = Sim $ do\n        r <- a\n        let (Sim k) = f r\n        k\n\ninstance MonadFix (Sim t) where\n    mfix f = Sim $ mfix (unSim . f)\n\n-------------------------------------------------------------------\n-- Network\n-------------------------------------------------------------------\n\n-- | This type family is used for determining the best way to store\n-- a vector of values. It should evaluate to something that is an\n-- instance of @Data.Vector.Generic.Vector@.\ntype family NetStoreVec a :: * -> *\ntype instance NetStoreVec Double = UV.Vector\ntype instance NetStoreVec Float = UV.Vector\ntype instance NetStoreVec Word = UV.Vector\ntype instance NetStoreVec Int = UV.Vector\ntype instance NetStoreVec (Fixed a) = V.Vector\ntype instance NetStoreVec Scientific = V.Vector\n\ntype NetStore t = NetStoreVec t t\ntype NetStoreMut t = G.Mutable (NetStoreVec t) t\n\ntype Time t = (NFData (NetStoreVec t t), Show t, G.Vector (NetStoreVec t) t, Show (NetStore t))\n\n-- | A `Network` represents a compiled simulation.\ndata Network t o = Network\n    { netIntState :: !(NetStore t)\n    , netIntDeriv :: !(IntMap (Signal t (NetStore t)))\n    , netFnTime   :: !(NetStore t)\n    , netRoot     :: (Signal t o)  -- TODO: Make this a container of signals?\n    } deriving (Generic)\n\n\n-- TODO: Rewrite\n\n-- | Cleans up a `Network` after a switching event, removing signals\n-- that are no longer needed.\ngc :: forall v t o. Time t => Network t o -> Network t o\ngc n@Network{..} =\n    let\n        (intAll, intReachable, fnReachable) = findNames netRoot\n\n        findNames :: Signal t a -> (IntSet, IntSet, IntSet)\n        findNames s = execState (go s)  mempty\n\n        go :: forall a. Signal t a -> State (IntSet, IntSet, IntSet) ()\n        go (SInt ix (f :: x -> a)) = do\n            (i,i',f) <- get\n            when (not $ Set.member ix i) $ do\n                let\n                    pt = Proxy :: Proxy t\n                    pa = Proxy :: Proxy x\n                    len = splen pt pa - 1\n                    names = Set.fromList [ix..ix + len]\n                put (i `Set.union` names, Set.insert ix i', f)\n                go (netIntDeriv IntMap.! ix)\n        go (SAp a b) = go a >> go b\n        go (SMap _ s) = go s\n        go (SAdd a b) = go a >> go b\n        go (SMul a b) = go a >> go b\n        go (SDiv a b) = go a >> go b\n        go (SPure _) = return ()\n        go (SFn ix _) = modify $ mappend (mempty, mempty, Set.singleton ix)\n        go (SSwitch s e) = go s >> goE e\n        go (SShare s) = go s\n\n        goE :: Event t a -> State (IntSet, IntSet, IntSet) ()\n        goE (ERoot s) = go s\n        goE (EMap _ e) = goE e\n        goE (ETag e s) = goE e >> go s\n\n        intMap  = UV.fromList (Set.toAscList intReachable)\n        intMapAll = UV.fromList (Set.toAscList intAll)\n        intMap' = IntMap.fromList $ zip (Set.toAscList intReachable) [0..]\n\n        fnMap   = UV.fromList (Set.toAscList fnReachable)\n        fnMap' = IntMap.fromList $ zip (Set.toAscList fnReachable) [0..]\n\n        rename :: Signal t a -> Signal t a\n        rename (SAp a b) = SAp (rename a) (rename b)\n        rename (SMap f a) = SMap f (rename a)\n        rename s@(SPure _) = s\n        rename (SInt ix f) = SInt (intMap' IntMap.! ix) f\n        rename (SFn ix f) = SFn (fnMap' IntMap.! ix) f\n        rename (SSwitch s e) = SSwitch (rename s) (renameE e)\n        rename (SShare s) = SShare (rename s)\n\n        renameE :: Event t a -> Event t a\n        renameE (ERoot s) = ERoot (rename s)\n        renameE (EMap f e) = EMap f (renameE e)\n        renameE (ETag e s) = ETag (renameE e) (rename s)\n\n        intCnt = UV.length intMap\n        fnCnt  = UV.length fnMap\n\n        intState' = G.generate intCnt $ \\ix -> netIntState G.! (intMapAll UV.! ix)\n\n        restrictKeys m s = IntMap.filterWithKey (\\k _ -> k `Set.member` s) m\n        intDeriv' = fmap rename $ restrictKeys netIntDeriv intReachable\n\n        fnTime' = G.generate fnCnt $ \\ix -> netFnTime G.! (fnMap UV.! ix)\n        root' = rename netRoot\n\n        -- intDeriv' = execWriter $ getDeriv root'\n\n    in n\n        { netIntState = intState'\n        , netIntDeriv = IntMap.mapKeys (\\k -> intMap' IntMap.! k) intDeriv'\n        , netFnTime = fnTime'\n        , netRoot = root'\n        }\n\neventOccured :: Time t => Network t o -> Network t o -> Event t a -> Maybe a\neventOccured old new (EMap f e) = f <$> eventOccured old new e\neventOccured old new (ETag e s) = flip (,) (evalSignal new s) <$> eventOccured old new e\neventOccured old new (ERoot s)\n    | oldS < 0 && 0 <= newS = Just ()\n    | newS <= 0 && 0 < oldS = Just ()\n    | otherwise = Nothing\n        where\n            oldS = evalSignal old s\n            newS = evalSignal new s\n\nrunSwitches' :: forall v t o. Time t => Network t o -> Network t o -> (Bool, Network t o)\nrunSwitches' old new =\n    let\n        go :: Signal t a -> WriterT Any (Sim t) (Signal t a)\n        go s@(SPure a) = return s\n        go (SMap f s) = go s >>= pure . SMap f\n        go (SAdd a b) = do\n            a' <- go a\n            b' <- go b\n            return $ SAdd a' b'\n        go (SMul a b) = do\n            a' <- go a\n            b' <- go b\n            return $ SMul a' b'\n        go (SDiv a b) = do\n            a' <- go a\n            b' <- go b\n            return $ SDiv a' b'\n        go (SAp f a) = do\n            f' <- go f\n            a' <- go a\n            return $ SAp f' a'\n        go s@(SInt _ _) = return s\n        go s@(SFn ix f) = return s\n        go (SSwitch s e) = case eventOccured old new e of\n            Just v -> tell (Any True) >> lift v\n            Nothing -> do\n                s' <- go s\n                e' <- goE e\n                return $ SSwitch s' e'\n        go (SShare s) = go s >>= pure . SShare\n\n        goE :: Event t a -> WriterT Any (Sim t) (Event t a)\n        goE (ERoot s) = go s >>= pure . ERoot\n        goE (EMap f e) = goE e >>= pure . EMap f\n        goE (ETag e s) = do\n            e' <- goE e\n            s' <- go s\n            return (ETag e' s')\n\n        (((root', derivs'), Any changed), net') = addSim new $ runWriterT $ do\n            newRoot <- go $ netRoot new\n            newDerivs <- mapM go $ netIntDeriv new\n            return (newRoot, newDerivs)\n    in\n        if changed\n        then (changed, gc $ net'\n            { netRoot = root'\n            , netIntDeriv = derivs'\n            })\n        else (changed, new)\n\nrunSwitches old new = snd $ runSwitches' old new\nanyEvent old new = fst $ runSwitches' old new\n\nnewDoubleSim :: Sim Double (Signal Double a) -> Network Double a\nnewDoubleSim = newSim\n\nnewSim :: Time t => Sim t (Signal t a) -> Network t a\nnewSim (Sim s) =\n    let\n        (r,n) = runState s Network\n            { netIntState = G.empty\n            , netIntDeriv = IntMap.empty\n            , netFnTime  = G.empty\n            , netRoot = r\n            }\n    in n\n\naddSim :: Time t => Network t o -> Sim t a -> (a, Network t o)\naddSim n (Sim s) = runState s n\n\n-- TODO: Below are three implementations of evalSignal. Each with different\n-- sharing characteristics.\n--  * evalSignal' does explicit sharing\n--  * evalSignal'' does no sharing\n--  * evalSignal''' does implicit sharing\n-- We need to benchmark and determine which is best.\n-- Once we determine which solution to go for, we should integrate it\n-- more with the rest of the code such that sharing caries over to\n-- events.\n--\n-- It's probably worth redefining `share` to `id` when not using sharing\n-- or using implicit sharing.\nevalSignal'\n    :: forall t o a. (Time t)\n    => Network t o -> Signal t a -> State (IntMap (StableName Prim.Any, Any)) a\nevalSignal' c me@(SShare s) = do\n    m <- get\n    let\n        name = unsafePerformIO $ makeStableName me\n        nameh = hashStableName name\n        mv = do\n            (n,v) <- IntMap.lookup nameh m\n            if eqStableName name n\n            then return $ unsafeCoerce v\n            else Nothing\n    case mv of\n        Just v -> return v\n        Nothing -> do\n            v' <- evalSignal' c s\n            put $ IntMap.insert nameh (unsafeCoerce name, unsafeCoerce v') m\n            return v'\nevalSignal' c (SPure a) = return a\nevalSignal' c (SAdd a b) = do\n    a' <- evalSignal' c a\n    b' <- evalSignal' c b\n    return $ a' + b'\nevalSignal' c (SMul a b) = do\n    a' <- evalSignal' c a\n    b' <- evalSignal' c b\n    return $ a' * b'\nevalSignal' c (SDiv a b) = do\n    a' <- evalSignal' c a\n    b' <- evalSignal' c b\n    return $ a' / b'\nevalSignal' c (SMap f s) = f <$> evalSignal' c s\nevalSignal' c (SAp f a) = do\n    f' <- evalSignal' c f\n    a' <- evalSignal' c a\n    return $ f' a'\nevalSignal' c (SFn ix f) = return $ f $ netFnTime c G.! ix\nevalSignal' c (SInt ix (f :: x -> a)) = do\n    let\n        len = splen (Proxy :: Proxy t) (Proxy :: Proxy x)\n    return $ f $ unsplat $ G.slice ix len (netIntState c)\nevalSignal' c (SSwitch s _) = evalSignal' c s\n\nevalSignal'' :: forall t o a. Time t => Network t o -> Signal t a -> a\nevalSignal'' c = go\n    where\n        go :: forall b. Signal t b -> b\n        go (SPure a) = a `seq` a\n        go (SMap f s) = let x = f $! go s in x `seq` x\n        go (SAdd a b) = let x = go a + go b in x `seq` x\n        go (SMul a b) = let x = go a * go b in x `seq` x\n        go (SDiv a b) = let x = go a / go b in x `seq` x\n        go (SAp f a) =\n            let\n                f' = go f\n                a' = go a\n                x = f' a'\n            in x `seq` x\n        go (SFn ix f) = let x = f $! netFnTime c G.! ix in x `seq` x\n        go (SInt ix (f :: x -> b)) = let x = f $! unsplat $ G.slice ix (splen (Proxy :: Proxy t) (Proxy :: Proxy x)) (netIntState c) in x `seq` x\n        go (SSwitch s _) = go s\n        go (SShare s) = go s\n\nevalSignal''' :: forall t o a. Time t => Network t o -> Signal t a -> a\nevalSignal''' c = go\n    where\n        go :: Signal t c -> c\n        go = memo gogo\n\n        gogo :: forall b. Signal t b -> b\n        gogo (SPure a) = a\n        gogo (SMap f s) = f $ go s\n        gogo (SAdd a b) = go a + go b\n        gogo (SMul a b) = go a * go b\n        gogo (SDiv a b) = go a / go b\n        gogo (SAp f a) = go f $ go a\n        gogo (SFn ix f) = f $ netFnTime c G.! ix\n        gogo (SInt ix (f :: x -> b)) = f $ unsplat $ G.slice ix (splen (Proxy :: Proxy t) (Proxy :: Proxy x)) (netIntState c)\n        gogo (SSwitch s _) = go s\n        gogo (SShare s) = go s\n\nevalSignal :: forall t o a. Time t => Network t o -> Signal t a -> a\n--evalSignal n s = evalState (evalSignal' n s) mempty\nevalSignal = evalSignal''\n--evalSignal = evalSignal'''\n--evalSignal n = memo (evalSignal'' n)\n--{-# NOINLINE evalSignal #-}\n\nevalRoot :: Time t => Network t o -> o\nevalRoot c = evalSignal c (netRoot c)\n\ndeltaNet :: (Num t, Time t) => Network t o -> t -> NetStore t -> Network t o\ndeltaNet n@Network{..} h dv = deltaNetState (deltaNetTime n h) dv\n\ndeltaNetState :: (Num t, Time t) => Network t o -> NetStore t -> Network t o\ndeltaNetState n@Network{..} dv = n\n    { netIntState = G.zipWith (+) netIntState dv\n    }\n\ndeltaNetTime :: (Num t, Time t) => Network t o -> t -> Network t o\ndeltaNetTime n@Network{..} h = n\n    { netFnTime  = G.map (+h) netFnTime\n    }\n\nderivs :: (Num t, Time t) => Network t o -> t -> NetStore t -> NetStore t\nderivs n h dv =\n    let\n        n' = deltaNet n h dv\n    in derivsNow n'\n\nderivsNow :: (Time t) => Network t o -> NetStore t\nderivsNow n = G.concat $ parMapChunk (evalSignal n . snd) $ IntMap.toAscList $ netIntDeriv n\n\n-- TODO: Why is this burning so much CPU and not giving me /that/ much of\n-- a speed up. Changing the chunk size doesn't seem to make that much\n-- difference.\n--\n-- 1 -N1  (100% cpu)\n-- real\t0m14.623s\n-- user\t0m14.458s\n-- sys\t0m0.149s\n--\n-- All the rest 580% cpu\n-- 1 -N\n-- real\t0m10.852s\n-- user\t0m39.608s\n-- sys\t0m22.108s\n--\n-- 20 -N\n-- real\t0m10.932s\n-- user\t0m35.629s\n-- sys\t0m23.757s\n--\n-- 200 -N\n-- real\t0m11.231s\n-- user\t0m37.745s\n-- sys\t0m24.182s\nparMapChunk f as =\n    let\n        a = map f as\n    in a `Par.using` Par.parListChunk 50 (Par.rdeepseq)\n\n-------------------------------------------------------------------\n-- Splat\n-------------------------------------------------------------------\n\nclass Splat t a where\n    splen :: Proxy t -> Proxy a -> Int\n    splat :: Time t => a -> NetStore t\n    unsplat :: Time t => NetStore t -> a\n\ninstance Splat t t where\n    splen _ _ = 1\n    splat t = G.singleton t\n    unsplat v = v G.! 0\n\ninstance Splat t (t,t) where\n    splen t _ = 2\n    splat (a,b) = splat a G.++ splat b\n    unsplat v = (v G.! 0, v G.! 1)\n\ninstance Splat t (t,t,t) where\n    splen t _ = 3\n    splat (a,b,c) = G.fromList [a,b,c]\n    unsplat v = (v G.! 0, v G.! 1, v G.! 2)\n\ninstance Splat t (t,t,t,t) where\n    splen t _ = 4\n    splat (a,b,c,d) = G.fromList [a,b,c,d]\n    unsplat v = (v G.! 0, v G.! 1, v G.! 2, v G.! 3)\n\ninstance Splat t (Complex t) where\n    splen t _ = 2\n    splat (a :+ b) = G.fromList [a,b]\n    unsplat v = (v G.! 0) :+ (v G.! 1)\n\ninstance Splat t (V1 t) where\n    splen t _ = splen t (Proxy :: Proxy t)\n    splat (V1 a) = splat a\n    unsplat = V1 . unsplat\n\ninstance Splat t (V2 t) where\n    splen t _ = splen t (Proxy :: Proxy (t,t))\n    splat (V2 a b) = splat (a,b)\n    unsplat v = let (a,b) = unsplat v in V2 a b\n\ninstance Splat t (V3 t) where\n    splen t _ = splen t (Proxy :: Proxy (t,t,t))\n    splat (V3 a b c) = splat (a,b,c)\n    unsplat v = let (a,b,c) = unsplat v in V3 a b c\n\ninstance Splat t (V4 t) where\n    splen t _ = splen t (Proxy :: Proxy (t,t,t,t))\n    splat (V4 a b c d) = splat (a,b,c,d)\n    unsplat v = let (a,b,c,d) = unsplat v in V4 a b c d\n\n-------------------------------------------------------------------\n-- API\n-------------------------------------------------------------------\n\n-- | Integrate the input `Signal` with respect to time.\nintegral :: (Splat t a, Time t) => a -> Signal t a -> Sim t (Signal t a)\nintegral i s = Sim $ do\n    st <- get\n    let\n        sp = splat i\n        ix = G.length (netIntState st)\n    put st\n        { netIntState = netIntState st G.++ sp\n        , netIntDeriv = IntMap.insert ix (fmap splat s) (netIntDeriv st)\n        }\n    return $ SInt ix id\n\n-- | Create a `Signal` that is a pure function of time. Each `timeFn'` has\n-- a local concept of time, and this time starts from the provided time\n-- value.\ntimeFn' :: Time t => t -> (t -> a) -> Sim t (Signal t a)\ntimeFn' t f = Sim $ do\n    st <- get\n    let\n        ix = G.length (netFnTime st)\n    put st\n        { netFnTime = netFnTime st `G.snoc` t\n        }\n    return $ SFn ix f\n\n-- | As `timeFn'` but local time starts at 0.\ntimeFn :: (Time t, Num t) => (t -> a) -> Sim t (Signal t a)\ntimeFn = timeFn' 0\n\n-- | Start out as the input `Signal`, but when the `Event` occurs, become\n-- the signal that it carries, and remain as that signal forever. Future\n-- `Event`s from this event source will be ignored. See `switch` for\n-- alternate behavior.\nbecome :: Signal t a -> Event t (Sim t (Signal t a)) -> Signal t a\nbecome = SSwitch\n\n-- | Start out as the input `Signal` and everytime the `Event` occurs, change\n-- to the new `Signal` carried in the `Event`. This can easily cause\n-- a space leak if used recursively. Look at `become` for a safer solution.\nswitch :: Signal t a -> Event t (Sim t (Signal t a)) -> Signal t a\nswitch s e = become s (fmap (\\s' -> s' >>= \\s'' -> pure (switch s'' e)) e)\n\n-- | Useful combination of `become` and `fmap`\nbecomeOn :: Signal t a -> Event t b -> (b -> Sim t (Signal t a)) -> Signal t a\nbecomeOn s e f = become s (fmap f e)\n\n-- | Turns the input `Signal t a` into a `Signal t (Maybe a)`, resulting\n-- in `Nothing` as soon as the `Event` fires, and remaining `Nothing` forever\n-- after that point.\nbecomeNothingOn :: Signal t a -> Event t b -> Signal t (Maybe a)\nbecomeNothingOn s e = becomeOn (fmap Just s) e $ \\_ -> return $ pure Nothing\n\n\n-- | Memoize the result of evaluating this Signal so that repeated\n-- uses don't have to re-evaluate everything. Integrations are\n-- already shared by default, so avoid sharing them directly.\n--\n-- TODO: Depending on the signal evaluation strategy (see comments in code)\n-- sharing may implicitly happen for all signals, or not at all.\nshare :: Signal t a -> Signal t a\nshare = SShare\n\n-- | Emit an event every time the input `Signal` crosses 0.\nroot :: (Ord t, Num t) => Signal t t -> Event t ()\nroot = ERoot\n\n-- | Tag the given event with the value of the signal when it occurs.\ntag :: Event t a -> Signal t b -> Event t (a,b)\ntag  = ETag\n\n-------------------------------------------------------------------\n-- Simulation\n-------------------------------------------------------------------\n\ndata SimResult t o = SimResult\n    { stepNumber :: !Integer\n    , globalTime :: !t\n    , result     :: !o\n    } deriving (Eq, Ord, Show, Functor)\n\nasTuple :: SimResult t o -> (t,o)\nasTuple (SimResult _ t o) = (t,o)\n\n-- | Run the `Integrator` over the given `Signal` outputting a list of\n-- time stamp and `Network`s.\nsimulate'\n    :: forall v t o. (Num t, Time t)\n    => Integrator t o -> Sim t (Signal t o) -> [SimResult t (Network t o)]\nsimulate' integrator s =\n    let\n        n = newSim s\n    in unfoldr (\\(cnt,i,n,t) ->\n        let\n            (n',r,i') =  runIntegrator i n\n            t' = t + r\n        in\n            cnt `seq` t `seq` n  `seq` (Just $!\n                ( SimResult cnt t n   -- Previous step\n                , (succ cnt, i', n', t')\n                ))\n        ) (0,integrator,n,0)\n\n-- | Run the `Integrator` over the given `Signal`, outputting a list of\n-- time stamp and signal values.\nsimulate :: (Num t, Time t) => Integrator t o -> Sim t (Signal t o) -> [SimResult t o]\nsimulate i s = fmap evalRoot <$> simulate' i s\n\n-- | Causes progress messages to be printed every 100 steps. Uses lazy IO,\n-- so be careful.\n--  TODO: Rejig things to be more streamy.\ntrace :: (Show t, Show o, PrintfArg t) => [SimResult t o] -> IO [SimResult t o]\ntrace [] = return []\ntrace (s@(SimResult c t o):rest)\n    | 0 == c `mod` 100 = do\n        printf \"S: %5d  T: %5.3v  V: \" c t\n        putStrLn $ show o\n        r <- unsafeInterleaveIO $ trace rest\n        return $ s : r\n    | otherwise = do\n        r <- unsafeInterleaveIO $ trace rest\n        return $ s : r\n\n-- | `simulate'` specialised to `Double`\nsimulateDouble'\n    :: Integrator Double o\n    -> Sim Double (Signal Double o)\n    -> [SimResult Double (Network Double o)]\nsimulateDouble' = simulate'\n\n-- | `simulate` specialised to `Double`\nsimulateDouble\n    :: Integrator Double o\n    -> Sim Double (Signal Double o)\n    -> [SimResult Double o]\nsimulateDouble = simulate\n\n-- | `simulate` which stops as soon as the `Signal` value becomes `Nothing`\nsimulateJust :: (Num t, Time t) => Integrator t (Maybe o) -> Sim t (Signal t (Maybe o)) -> [SimResult t o]\nsimulateJust i s = fmap (\\(SimResult n t (Just x)) -> SimResult n t x) $ takeWhile (isJust . result) $ simulate i s\n\n-- | `simulateJust` specialised to `Double`\nsimulateJustDouble :: Integrator Double (Maybe o) -> Sim Double (Signal Double (Maybe o)) -> [SimResult Double o]\nsimulateJustDouble = simulateJust\n\n-- | Simulate until the specified time is reached. The termination time is\n-- marked by an `Event`, meaning that adaptive integration methods which\n-- narrow down on event locations will be do so to get accurate finishing\n-- times.\nsimulateUntil :: (Ord t, Num t, Time t) => t -> Integrator t (Maybe o) -> Sim t (Signal t o) -> [SimResult t o]\nsimulateUntil duration i s = simulateJust i $ do\n    t <- timer duration\n    s' <- s\n    return $ s' `becomeNothingOn` t\n\n-- | `simulateUntil` specialised to `Double`\nsimulateUntilDouble :: Double -> Integrator Double (Maybe o) -> Sim Double (Signal Double o) -> [SimResult Double o]\nsimulateUntilDouble = simulateUntil\n\n-- | Run a simulation in real time, printing the result values to the terminal.\nrunRk4RealTime :: forall a. Show a => Sim Double (Signal Double a) -> IO ()\nrunRk4RealTime s =\n    let\n        n = newSim s\n        go :: UTCTime -> Network Double a -> IO ()\n        go prev n = do\n            now <- getCurrentTime\n            let\n                h = realToFrac $ diffUTCTime now prev\n                (n',_,_) = runIntegrator (rk4 h) n\n            print $ evalRoot n'\n            go now n'\n    in do\n        now <- getCurrentTime\n        go now n\n\n-- | Same as `runRk4RealTime` but stops when a `Nothing` value is produced.\nrunRk4RealTimeJust :: forall a. Show a => Sim Double (Signal Double (Maybe a)) -> IO ()\nrunRk4RealTimeJust s =\n    let\n        n = newSim s\n        go :: UTCTime -> Network Double (Maybe a) -> IO ()\n        go prev n = do\n            now <- getCurrentTime\n            let\n                h = realToFrac $ diffUTCTime now prev\n                (n',_,_) = runIntegrator (rk4 h) n\n            case evalRoot n' of\n                Nothing -> return ()\n                Just x -> print x >> go now n'\n    in do\n        now <- getCurrentTime\n        go now n\n\nsample :: (Ord t, Real t) => t -> [(t,a)] -> [(t,a)]\nsample freq = go 500\n    where\n        go _ [] = []\n        go n ((t,r):xs)\n            | t' < n = (t,r) : go t' xs\n            | otherwise = go t' xs\n            where\n                t' = t `mod'` freq\n\n-------------------------------------------------------------------\n-- Integrators\n-------------------------------------------------------------------\n\nnewtype Integrator t o = Integrator\n    { runIntegrator :: Network t o -> (Network t o, t, Integrator t o)\n    } deriving Generic\n\ninstance NFData (Integrator t o)\n\neulerSimple :: (Num t, Time t) => t -> Integrator t o\neulerSimple h = integrator\n    where\n        integrator = Integrator go\n        go n =\n            let\n                ds = derivsNow n\n                n' = deltaNet n h (G.map (*h) ds)\n            in (runSwitches n n', h, integrator)\n\n-- | Same as `euler` except that it bisects around `Event`s until it is within\n-- the provided tolerance.\neulerBisect :: (Fractional t, Ord t, Time t) => t -> t -> Integrator t o\neulerBisect tol h = integrator\n    where\n        integrator = Integrator $ go h\n        go h' n =\n            let\n                ds = derivsNow n\n                n' = deltaNet n h' (G.map (*h') ds)\n                (e,n'') = runSwitches' n n'\n                res\n                    -- TODO: Don't emit nearby points, jump strait to it.\n                    | e && h' > tol = go (h'/2) n\n                    | otherwise = (n'', h', integrator)\n            in res\n\n-- | Configuration for adaptive methods.\n--\n-- Unchecked assumptions: 0 < `minStep` < `eventTolerance` < `maxStep`\ndata AdaptiveConfig t = AdaptiveConfig\n    { minStep :: Maybe t\n    , maxStep :: Maybe t\n    , tolerance :: t\n    , eventTolerance :: t\n    }\n\ninstance Fractional t => Default (AdaptiveConfig t) where\n    def = AdaptiveConfig\n        { minStep = Nothing\n        , maxStep = Nothing\n        , tolerance = 0.001\n        , eventTolerance = 0.001\n        }\n\n-- If maxStep < minStep, we choose maxStep always.\nadaptiveClamp :: Ord t => AdaptiveConfig t -> t -> t\nadaptiveClamp AdaptiveConfig{..} t =\n    let\n        t' = maybe t (max t) minStep\n    in\n        maybe t' (min t') maxStep\n\nclamp :: Ord a => a -> a -> a -> a\nclamp l h t\n    | t < l = l\n    | t > h = h\n    | otherwise = t\n\neuler :: (Ord t, Fractional t, Time t, Show t) => AdaptiveConfig t -> Integrator t o\neuler conf@AdaptiveConfig{..} = Integrator $ go 0.1\n    where\n        go h n =\n            let\n                eulStep h n = deltaNet n h (G.map (*h) (derivsNow n))\n\n                n10  = eulStep h n\n                n1_2 = eulStep (h/2) n\n                n11  = eulStep (h/2) n1_2\n                tau  = G.zipWith (-) (netIntState n11) (netIntState n10)\n                tau' = G.maximum $ G.map abs tau\n                n12  = deltaNetState n11 tau\n\n                h' = adaptiveClamp conf $ 0.9 * h * clamp 0.3 3 (tolerance / tau')\n\n                (e,n') = runSwitches' n n12\n\n                res\n                    | e && h > eventTolerance && h > fromMaybe 0 minStep\n                        = go (adaptiveClamp conf (h/2)) n\n                    | tau' > tolerance && h' > fromMaybe 0 minStep = go h' n\n                    | otherwise = (n', h, Integrator $ go h')\n            in res\n\nrk4 :: (Fractional t, Time t) => t -> Integrator t o\nrk4 h = integrator\n    where\n        integrator = Integrator go\n        go n =\n            let\n                h2 = h / 2\n                h6 = h / 6\n                k1 = derivsNow n\n                k2 = derivs n h2 (G.map (*h2) k1)\n                k3 = derivs n h2 (G.map (*h2) k2)\n                k4 = derivs n h  (G.map (*h)  k3)\n                n' = deltaNet n h (G.map (* h6)\n                    $ G.zipWith4 (\\a b c d -> a + 2 * b + 2 * c + d) k1 k2 k3 k4)\n            in\n                (runSwitches n n', h, integrator)\n\n\n-------------------------------------------------------------------\n-- Visualisation\n-------------------------------------------------------------------\n\nclass Plot a where\n    plot :: [SimResult Double a] -> Chart.EC (Chart.Layout Double Double) ()\n\nnewtype a ::: (name :: Symbol) = Named a\n    deriving (Read,Enum,Real,RealFrac,RealFloat,Eq,Ord,Show,Num,Fractional,Floating,Chart.PlotValue)\n\ninfixr 0 :::\n\ninstance Plot Double where\n    plot = Chart.plot . Chart.points \"\" . fmap asTuple\n\ninstance (KnownSymbol name, Chart.PlotValue a) => Plot (a ::: name) where\n    plot = Chart.plot . Chart.points name . fmap (fmap Chart.toValue) . fmap asTuple\n        where\n            name = symbolVal (Proxy :: Proxy name)\n\ninstance (Plot a, Plot b) => Plot (a,b) where\n    plot as = do\n        plot (fmap fst <$> as)\n        plot (fmap snd <$> as)\n\ninstance (Plot a, Plot b, Plot c) => Plot (a,b,c) where\n    plot as = do\n        plot (fmap (\\(a,_,_) -> a) <$> as)\n        plot (fmap (\\(_,b,_) -> b) <$> as)\n        plot (fmap (\\(_,_,c) -> c) <$> as)\n\ninstance Plot a => Plot (V2 a) where\n    plot as = do\n        plot (fmap (Chart.^. _x) <$> as)\n        plot (fmap (Chart.^. _y) <$> as)\n\ninstance Plot a => Plot (V4 a) where\n    plot as = do\n        plot (fmap (Chart.^. _x) <$> as)\n        plot (fmap (Chart.^. _y) <$> as)\n        plot (fmap (Chart.^. _z) <$> as)\n        plot (fmap (Chart.^. _w) <$> as)\n\nplotSimUntil\n    :: Plot o\n    => Double\n    -> Integrator Double (Maybe o)\n    -> Sim Double (Signal Double o)\n    -> Chart.EC (Chart.Layout Double Double) ()\nplotSimUntil t i s = plot (simulateUntil t i s)\n\nplotSimUntilToFile n title t i s = do\n    r <- trace $ simulateUntil t i s\n    Chart.toFile Chart.def n $ do\n        Chart.layout_title Chart..= title\n        plot r\n\nclass PlotPara a where\n    plotPara :: [SimResult Double a] -> Chart.EC (Chart.Layout Double Double) ()\n\ninstance PlotPara (V2 Double) where\n    plotPara = Chart.plot . Chart.line \"\" . (:[]) . fmap (\\(SimResult n t (V2 a b)) -> (a,b))\n\ninstance (KnownSymbol name) => PlotPara (V2 Double ::: name) where\n    plotPara = Chart.plot . Chart.line name . (:[]) . fmap (\\(SimResult n t (Named (V2 a b))) -> (a,b))\n        where\n            name = symbolVal (Proxy :: Proxy name)\n\ninstance (PlotPara a, PlotPara b) => PlotPara (a,b) where\n    plotPara as = do\n        plotPara (fmap fst <$> as)\n        plotPara (fmap snd <$> as)\n\ninstance (PlotPara a, PlotPara b, PlotPara c) => PlotPara (a,b,c) where\n    plotPara as = do\n        plotPara (fmap (\\(a,_,_) -> a) <$> as)\n        plotPara (fmap (\\(_,b,_) -> b) <$> as)\n        plotPara (fmap (\\(_,_,c) -> c) <$> as)\n\ninstance PlotPara (Map String (V2 Double)) where\n    plotPara [] = return ()\n    plotPara as@(SimResult _ _ a : _) = do\n        let\n            ks = Map.keys a\n            kk = if length ks > 10 then \\_ -> \"\" else id\n        forM_ a $ \\(V2 x y) -> do\n            Chart.plot $ Chart.points \"\" [(x,y)]\n        forM_ ks $ \\k -> do\n            Chart.plot $ Chart.line (kk k) . (:[]) $ fmap (\\(SimResult n t m) ->\n                let\n                    V2 a b = m Map.! k\n                in (a,b)\n                ) as\n\nplotParaSimUntil\n    :: PlotPara o\n    => Double\n    -> Integrator Double (Maybe o)\n    -> Sim Double (Signal Double o)\n    -> Chart.EC (Chart.Layout Double Double) ()\nplotParaSimUntil t i s = plotPara $ simulateUntil t i s\n\nplotParaSimUntilToFile n title t i s = do\n    r <- trace $ simulateUntil t i s\n    Chart.toFile Chart.def n $ do\n        Chart.layout_title Chart..= title\n        plotPara r\n\n-------------------------------------------------------------------\n-- Utility\n-------------------------------------------------------------------\n\n-- | Applicative tupples\n(-:) :: Applicative f => f a -> f b -> f (a,b)\n(-:) = liftA2 (,)\ninfixr 5 -:\n\n-- | Applicative `Named` tuples.\n(-::) :: Applicative f => f a -> f b -> f (a ::: an, b ::: bn)\na -:: b = (,) <$> (Named <$> a) <*> (Named <$> b)\ninfixr 5 -::\n\nthreeNames :: Applicative f => f a -> f b -> f c -> f (a ::: an, b ::: nm, c ::: cn)\nthreeNames a b c = (,,) <$> (Named <$> a) <*> (Named <$> b) <*> (Named <$> c)\n\n-------------------------------------------------------------------\n-- Examples/Test\n-------------------------------------------------------------------\n\n-- Ex1 demonstrates basic integration with recursion.\nex1 :: (Time t, Fractional t) => Sim t (Signal t (t, t))\nex1 = do\n    rec a <- integral 0.5 a\n    b <- integral 0 1\n    return $ a -: b\n\n-- Ex2 shows how to use `become` to change a singal to a new one upon\n-- an event.\nex2 :: forall t. (Fractional t, Ord t, Time t) => Sim t (Signal t t)\nex2 = do\n    t <- integral 5 (-1)\n    let\n        e = root t\n        e' = fmap (const $ pure 3) e\n    return $ become 1 e'\n\n-- Ex3 show the use of `switch` to control a signal.\nex3 :: (Time t, Floating t, Ord t) => Sim t (Signal t (t,t))\nex3 = do\n    t <- timeFn sin\n    let\n        e = tag (root t) (signum t)\n        e' = fmap (\\(_,v) -> return $ pure v) e\n    return $ (,) <$> t <*> switch 0 e'\n\n\n-- Ex4 can be used to demonstrate the accuracy of various integrators.\nex4\n    :: (Floating t, Time t)\n    => Sim t (Signal t\n        ( t ::: \"sin(t)\"\n        , t ::: \"\u222b\u222b\u222b\u222bsin(t)\"\n        ))\nex4 = do\n    s <- timeFn sin\n    s' <- integral (-1) s >>= integral 0 >>= integral 1 >>= integral 0\n    return $ s -:: s'\n\n-- Ex5 demonstrates using `Maybe` to terminate a simulation with\n-- `simulateJust`.\n--\n-- Note: The use of an `Event` rather than `fmap`ing over the signal\n-- causes the root finding algorithm of many integrators to kick in allowing\n-- for very precise finishing times.\nex5 :: (Floating t, Time t, Ord t) => Sim t (Signal t (Maybe (V4 t)))\nex5 = do\n    i <- (integral 0 $ pure (V4 0 1 2 (-0.5)) )\n    let\n        s = fmap (\\i -> 5 - norm i) i\n        e = root s\n    return $ i `becomeNothingOn` e\n\n-- Ex6 demonstrates the use of `share` to reduce the number\n-- of times a signal is evaluated. The trace will show\n-- \"Calc A\" once, but \"Calc B\" twice when using an explicit\n-- sharing eval strategy.\nex6 :: (Time t, Floating t) => Sim t (Signal t (V4 t))\nex6 = do\n    let\n        a = share $ fmap (Dbg.trace \"Calc A\") $ 5 + 2\n        b = fmap (Dbg.trace \"Calc B\") $ 5 + 2\n    return $ V4 <$> a <*> a <*> b <*> b\n\nex7 :: (Ord t, Floating t, Time t) => Sim t (Signal t t)\nex7 = do\n    s <- timeFn sin\n    let\n        e = root s\n        s1 = becomeOn 0 e (\\_ -> pure $ signum s)\n    integral 0 s1\n\ntimer :: (Num t, Time t, Ord t) => t -> Sim t (Event t ())\ntimer duration = timeFn (\\t -> duration - t) >>= pure . root\n\nstepAndHold :: (Num t, Ord t, Time t) => [(t,Sim t (Signal t a))] -> Sim t (Signal t a) -> Sim t (Signal t a)\nstepAndHold [] a = a\nstepAndHold ((t,a):ls) last = do\n    e <- timer t\n    s <- a\n    return $ s `becomeOn` e $ \\_ -> stepAndHold ls last\n\nex8 :: (Ord t, Floating t, Time t) => Sim t (Signal t (Maybe (t ::: \"Deriv\",t ::: \"Integral\")))\nex8 = do\n    t <- timer 6\n    d <- stepAndHold [(0.5,1),(0.2, -2),(1,0)] (timeFn sin)\n    i <- integral 0 d\n    let r = d -:: i\n    return $ r `becomeNothingOn` t\n\nex9\n    :: forall t. (Floating t, Time t)\n    => Sim t (Signal t \n        ( V2 t ::: \"Sun\"\n        , V2 t ::: \"Earth\"\n        , V2 t ::: \"Moon\"\n        ))\nex9 = do\n    rec\n        let\n            degRad :: t -> t\n            degRad t = t / 180 * pi\n\n            pos2init = 149.6e9 *^ angle $ degRad 3.201e2\n            pos3init = pos2init + 384.4e6 *^ angle (degRad 2.0644e2)\n\n        pos1 <- integral (V2 0 0) vel1\n        pos2 <- integral pos2init vel2\n        pos3 <- integral pos3init vel3\n\n        let\n            vel2init = 29766.42101876582 *^ signorm (perp pos2init)\n            vel3init = vel2init + 1023.005 *^ (signorm (perp pos3init))\n        vel1 <- integral (V2 0 0) acc1\n        vel2 <- integral vel2init acc2\n        vel3 <- integral vel3init acc3\n\n        let\n            g = 6.674e-11\n            m1 = 1.9891e30\n            m2 = 5.972e24\n            m3 = 7.347e22\n            -- f = g * m1 * m2 / r^2 = m1 * a\n            dir :: Signal t (V2 t) -> Signal t (V2 t) -> Signal t t -> Signal t (V2 t)\n            dir a b c =\n                let\n                    d = (^-^) <$> b <*> a\n                    u = signorm <$> d\n                in (*^) <$> c <*> u\n            f1 = sum\n                [ dir pos1 pos2 $ g * m1 * m2 / (qd <$> pos1 <*> pos2)\n                , dir pos1 pos3 $ g * m1 * m3 / (qd <$> pos1 <*> pos3)\n                ]\n            f2 = sum\n                [ dir pos2 pos1 $ g * m2 * m1 / (qd <$> pos2 <*> pos1)\n                , dir pos2 pos3 $ g * m2 * m3 / (qd <$> pos2 <*> pos3)\n                ]\n            f3 = sum\n                [ dir pos3 pos1 $ g * m3 * m1 / (qd <$> pos3 <*> pos1)\n                , dir pos3 pos2 $ g * m3 * m2 / (qd <$> pos3 <*> pos2)\n                ]\n            acc1 = (^/) <$> f1 <*> m1\n            acc2 = (^/) <$> f2 <*> m2\n            acc3 = (^/) <$> f3 <*> m3\n    return $ threeNames pos1 pos2 pos3\n", "meta": {"hexsha": "d4c435efceccbbd2e58b6666af39c16d619cc9b8", "size": 40136, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Dynamical/Sim/Internal.hs", "max_stars_repo_name": "luke-clifton/dynamical", "max_stars_repo_head_hexsha": "fa587c6f50d830f3515e0dcc5830b1a3279e70e2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Dynamical/Sim/Internal.hs", "max_issues_repo_name": "luke-clifton/dynamical", "max_issues_repo_head_hexsha": "fa587c6f50d830f3515e0dcc5830b1a3279e70e2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Dynamical/Sim/Internal.hs", "max_forks_repo_name": "luke-clifton/dynamical", "max_forks_repo_head_hexsha": "fa587c6f50d830f3515e0dcc5830b1a3279e70e2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6429170159, "max_line_length": 145, "alphanum_fraction": 0.5389924258, "num_tokens": 12175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.18572648192597144}}
{"text": "\n{-# LANGUAGE CPP #-}\n\n{-# LANGUAGE MultiParamTypeClasses  #-} -- for 'Bind' class.\n{-# LANGUAGE ConstraintKinds        #-} -- for 'Bind' class.\n{-# LANGUAGE TypeFamilies           #-} -- for 'Bind' class.\n\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE NoImplicitPrelude #-}\n\n{-# LANGUAGE UndecidableInstances #-}\n\n{-# LANGUAGE TypeOperators #-} -- For ':*:' instance and others.\n\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\n-- Some of the constraints may be unnecessary, but they are intentional.\n-- This is especially true for the 'Fail' instances.\n{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}\n#endif\n\n-- | Definition of supermonads that support constrained monads.\nmodule Control.Super.Monad.Constrained \n  ( -- * Supermonads\n    Bind(..), Return(..), Fail(..)\n    -- * Super-Applicatives\n  , Applicative(..), pure\n  , Functor(..)\n    -- * Conveniences\n  , Monad\n  ) where\n\nimport GHC.Exts ( Constraint )\n\nimport Prelude\n  ( String, Maybe, Either\n  , Ord\n  , (.), ($), const\n  )\nimport qualified Prelude as P\n\n\n-- To define instances:\nimport Data.Functor.Identity ( Identity(..) )\n\nimport qualified Data.Monoid as Mon\nimport qualified Data.Proxy as Proxy\nimport qualified Data.Functor.Product as Product\nimport qualified Data.Functor.Compose as Compose\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\nimport qualified Data.Complex as Complex\nimport qualified Data.Semigroup as Semigroup\nimport qualified Data.List.NonEmpty as NonEmpty\n#endif\n\nimport qualified Control.Arrow as Arrow\nimport qualified Control.Applicative as App\nimport qualified Control.Monad.ST as ST\nimport qualified Control.Monad.ST.Lazy as STL\n\nimport qualified Text.ParserCombinators.ReadP as Read\nimport qualified Text.ParserCombinators.ReadPrec as Read\n\nimport qualified GHC.Conc as STM\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\nimport qualified GHC.Generics as Generics\n#endif\n\n-- To defined constrained instances:\nimport qualified Data.Set as S\n\n-- To define \"transformers\" instances:\nimport qualified Control.Monad.Trans.Cont     as Cont\nimport qualified Control.Monad.Trans.Except   as Except\nimport qualified Control.Monad.Trans.Identity as Identity\nimport qualified Control.Monad.Trans.Maybe    as Maybe\nimport qualified Control.Monad.Trans.RWS.Lazy      as RWSL\nimport qualified Control.Monad.Trans.RWS.Strict    as RWSS\nimport qualified Control.Monad.Trans.Reader        as Reader\nimport qualified Control.Monad.Trans.State.Lazy    as StateL\nimport qualified Control.Monad.Trans.State.Strict  as StateS\nimport qualified Control.Monad.Trans.Writer.Lazy   as WriterL\nimport qualified Control.Monad.Trans.Writer.Strict as WriterS\n\n-- To define 'Bind' class:\nimport Control.Super.Monad.Constrained.Functor \n  ( Functor(..) )\n\n-- -----------------------------------------------------------------------------\n-- Super-Applicative Type Class\n-- -----------------------------------------------------------------------------\n\ninfixl 4 <*>, <*, *>\n\n-- | TODO\nclass (Functor m, Functor n, Functor p) => Applicative m n p where\n  type ApplicativeCts m n p (a :: *) (b :: *) :: Constraint\n  type ApplicativeCts m n p a b = ()\n  \n  type ApplicativeCtsR m n p (a :: *) (b :: *) :: Constraint\n  type ApplicativeCtsR m n p a b = ApplicativeCts m n p a b\n  \n  type ApplicativeCtsL m n p (a :: *) (b :: *) :: Constraint\n  type ApplicativeCtsL m n p a b = ApplicativeCts m n p a b \n  \n  (<*>) :: (ApplicativeCts m n p a b) => m (a -> b) -> n a -> p b\n  \n  -- TODO: Cannot give standard instances, because they would require \n  -- different constraints.\n  (*>) :: (ApplicativeCtsR m n p a b) => m a -> n b -> p b\n  --ma *> nb = (P.id <$ ma) <*> nb\n  --ma *> nb = (pure P.id <*> ma) <*> nb\n  \n  (<*) :: (ApplicativeCtsL m n p a b) => m a -> n b -> p a\n  --ma <* nb = fmap const ma <*> nb\n  --ma <* nb = (pure const <*> ma) <*> nb\n  \n\n-- | 'pure' is defined in terms of return.\npure :: (Return f, ReturnCts f a) => a -> f a\npure = return\n\ntype family DefaultAppCtsR m n p a b :: Constraint where\n  DefaultAppCtsR m n p a b = (ApplicativeCts m n p b b, FunctorCts m a (b -> b))\n\ntype family DefaultAppCtsL m n p a b :: Constraint where\n  DefaultAppCtsL m n p a b = (ApplicativeCts m n p b a, FunctorCts m a (b -> a))\n\ndefaultAppR :: (Applicative m n p, DefaultAppCtsR m n p a b) => m a -> n b -> p b\ndefaultAppR ma nb = (P.id <$ ma) <*> nb\n\ndefaultAppL :: (Applicative m n p, DefaultAppCtsL m n p a b) => m a -> n b -> p a\ndefaultAppL ma nb = fmap const ma <*> nb\n\n-- Standard Instances ----------------------------------------------------------\n\ninstance Applicative ((->) r) ((->) r) ((->) r) where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Identity Identity Identity where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative [] [] [] where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Maybe Maybe Maybe where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative P.IO P.IO P.IO where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative (Either e) (Either e) (Either e) where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n\ninstance Applicative Mon.First Mon.First Mon.First where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Mon.Last Mon.Last Mon.Last where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Applicative Mon.Sum Mon.Sum Mon.Sum where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Mon.Product Mon.Product Mon.Product where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Mon.Dual Mon.Dual Mon.Dual where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n#endif\ninstance (Applicative m n p) => Applicative (Mon.Alt m) (Mon.Alt n) (Mon.Alt p) where\n  type ApplicativeCts (Mon.Alt m) (Mon.Alt n) (Mon.Alt p) a b = ApplicativeCts m n p a b\n  type ApplicativeCtsR (Mon.Alt m) (Mon.Alt n) (Mon.Alt p) a b = ApplicativeCtsR m n p a b\n  type ApplicativeCtsL (Mon.Alt m) (Mon.Alt n) (Mon.Alt p) a b = ApplicativeCtsL m n p a b\n  mf <*> na = Mon.Alt $ (Mon.getAlt mf) <*> (Mon.getAlt na)\n  mf *> na = Mon.Alt $ (Mon.getAlt mf) *> (Mon.getAlt na)\n  mf <* na = Mon.Alt $ (Mon.getAlt mf) <* (Mon.getAlt na)\n\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Applicative Semigroup.Min Semigroup.Min Semigroup.Min where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Semigroup.Max Semigroup.Max Semigroup.Max where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Semigroup.Option Semigroup.Option Semigroup.Option where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Semigroup.First Semigroup.First Semigroup.First where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Semigroup.Last Semigroup.Last Semigroup.Last where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n#endif\n\ninstance Applicative Proxy.Proxy Proxy.Proxy Proxy.Proxy where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Applicative Complex.Complex Complex.Complex Complex.Complex where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative NonEmpty.NonEmpty NonEmpty.NonEmpty NonEmpty.NonEmpty where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n#endif\n\ninstance (Applicative m1 n1 p1, Applicative m2 n2 p2) => Applicative (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) where\n  type ApplicativeCts (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) a b = (ApplicativeCts m1 n1 p1 a b, ApplicativeCts m2 n2 p2 a b)\n  type ApplicativeCtsR (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) a b = (ApplicativeCtsR m1 n1 p1 a b, ApplicativeCtsR m2 n2 p2 a b)\n  type ApplicativeCtsL (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) a b = (ApplicativeCtsL m1 n1 p1 a b, ApplicativeCtsL m2 n2 p2 a b)\n  Product.Pair m1 m2 <*> Product.Pair n1 n2 = Product.Pair (m1 <*> n1) (m2 <*> n2)\n  Product.Pair m1 m2  *> Product.Pair n1 n2 = Product.Pair (m1  *> n1) (m2  *> n2)\n  Product.Pair m1 m2 <*  Product.Pair n1 n2 = Product.Pair (m1 <*  n1) (m2 <*  n2)\n\ninstance (Applicative f g h, Applicative f' g' h') => Applicative (Compose.Compose f f') (Compose.Compose g g') (Compose.Compose h h') where\n  type ApplicativeCts  (Compose.Compose f f') (Compose.Compose g g') (Compose.Compose h h') a b = ( ApplicativeCts f g h (g' a) (h' b), ApplicativeCts  f' g' h' a b\n                                                                                                  , FunctorCts f (f' (a -> b)) (g' a -> h' b) )\n  type ApplicativeCtsL (Compose.Compose f f') (Compose.Compose g g') (Compose.Compose h h') a b = ( ApplicativeCts f g h (g' b) (h' a), ApplicativeCtsL f' g' h' a b\n                                                                                                  , FunctorCts f (f' a) (g' b -> h' a) )\n  type ApplicativeCtsR (Compose.Compose f f') (Compose.Compose g g') (Compose.Compose h h') a b = ( ApplicativeCts f g h (g' b) (h' b), ApplicativeCtsR f' g' h' a b\n                                                                                                  , FunctorCts f (f' a) (g' b -> h' b) )\n  Compose.Compose f <*> Compose.Compose x = Compose.Compose $ fmap (<*>) f <*> x\n  Compose.Compose f  *> Compose.Compose x = Compose.Compose $ fmap ( *>) f <*> x\n  Compose.Compose f <*  Compose.Compose x = Compose.Compose $ fmap (<* ) f <*> x\n\ninstance Applicative Read.ReadP Read.ReadP Read.ReadP where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative Read.ReadPrec Read.ReadPrec Read.ReadPrec where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n\ninstance Applicative (ST.ST s) (ST.ST s) (ST.ST s) where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance Applicative (STL.ST s) (STL.ST s) (STL.ST s) where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n\ninstance (Arrow.Arrow a, Arrow.ArrowApply a) => Applicative (Arrow.ArrowMonad a) (Arrow.ArrowMonad a) (Arrow.ArrowMonad a) where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n\ninstance (Applicative m n p) => Applicative (App.WrappedMonad m) (App.WrappedMonad n) (App.WrappedMonad p) where\n  type ApplicativeCts (App.WrappedMonad m) (App.WrappedMonad n) (App.WrappedMonad p) a b = ApplicativeCts m n p a b\n  type ApplicativeCtsR (App.WrappedMonad m) (App.WrappedMonad n) (App.WrappedMonad p) a b = ApplicativeCtsR m n p a b\n  type ApplicativeCtsL (App.WrappedMonad m) (App.WrappedMonad n) (App.WrappedMonad p) a b = ApplicativeCtsL m n p a b\n  mf <*> na = App.WrapMonad $ (App.unwrapMonad mf) <*> (App.unwrapMonad na)\n  mf  *> na = App.WrapMonad $ (App.unwrapMonad mf)  *> (App.unwrapMonad na)\n  mf <*  na = App.WrapMonad $ (App.unwrapMonad mf) <*  (App.unwrapMonad na)\n\ninstance Applicative STM.STM STM.STM STM.STM where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\n\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Applicative Generics.U1 Generics.U1 Generics.U1 where\n  (<*>) = (P.<*>)\n  (<*)  = (P.<*)\n  (*>)  = (P.*>)\ninstance (Applicative f g h) => Applicative (Generics.Rec1 f) (Generics.Rec1 g) (Generics.Rec1 h) where\n  type ApplicativeCts  (Generics.Rec1 f) (Generics.Rec1 g) (Generics.Rec1 h) a b = ApplicativeCts  f g h a b\n  type ApplicativeCtsR (Generics.Rec1 f) (Generics.Rec1 g) (Generics.Rec1 h) a b = ApplicativeCtsR f g h a b\n  type ApplicativeCtsL (Generics.Rec1 f) (Generics.Rec1 g) (Generics.Rec1 h) a b = ApplicativeCtsL f g h a b\n  (Generics.Rec1 mf) <*> (Generics.Rec1 ma) = Generics.Rec1 $ mf <*> ma\n  (Generics.Rec1 mf)  *> (Generics.Rec1 ma) = Generics.Rec1 $ mf  *> ma\n  (Generics.Rec1 mf) <*  (Generics.Rec1 ma) = Generics.Rec1 $ mf <*  ma\ninstance (Applicative f g h, Applicative f' g' h') => Applicative (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') where\n  type ApplicativeCts  (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') a b = (ApplicativeCts  f g h a b, ApplicativeCts  f' g' h' a b)\n  type ApplicativeCtsL (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') a b = (ApplicativeCtsL f g h a b, ApplicativeCtsL f' g' h' a b)\n  type ApplicativeCtsR (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') a b = (ApplicativeCtsR f g h a b, ApplicativeCtsR f' g' h' a b)\n  (f Generics.:*: g) <*> (f' Generics.:*: g') = (f <*> f') Generics.:*: (g <*> g')\n  (f Generics.:*: g)  *> (f' Generics.:*: g') = (f  *> f') Generics.:*: (g  *> g')\n  (f Generics.:*: g) <*  (f' Generics.:*: g') = (f <*  f') Generics.:*: (g <*  g')\n-- TODO: Is there a nicer way to implement this for ':.:'?\ninstance (Applicative f g h, Applicative f' g' h') => Applicative (f Generics.:.: f') (g Generics.:.: g') (h Generics.:.: h') where\n  type ApplicativeCts  (f Generics.:.: f') (g Generics.:.: g') (h Generics.:.: h') a b = ( ApplicativeCts f g h (g' a) (h' b), ApplicativeCts  f' g' h' a b\n                                                                                         , FunctorCts f (f' (a -> b)) (g' a -> h' b) )\n  type ApplicativeCtsL (f Generics.:.: f') (g Generics.:.: g') (h Generics.:.: h') a b = ( ApplicativeCts f g h (g' b) (h' a), ApplicativeCtsL f' g' h' a b\n                                                                                         , FunctorCts f (f' a) (g' b -> h' a) )\n  type ApplicativeCtsR (f Generics.:.: f') (g Generics.:.: g') (h Generics.:.: h') a b = ( ApplicativeCts f g h (g' b) (h' b), ApplicativeCtsR f' g' h' a b\n                                                                                         , FunctorCts f (f' a) (g' b -> h' b) )\n  (Generics.Comp1 mf) <*> (Generics.Comp1 ma) = Generics.Comp1 $ fmap (<*>) mf <*> ma\n  (Generics.Comp1 ma)  *> (Generics.Comp1 mb) = Generics.Comp1 $ fmap ( *>) ma <*> mb\n  (Generics.Comp1 ma) <*  (Generics.Comp1 mb) = Generics.Comp1 $ fmap (<* ) ma <*> mb\ninstance Applicative f g h => Applicative (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) where\n  type ApplicativeCts  (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) a b = ApplicativeCts  f g h a b\n  type ApplicativeCtsL (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) a b = ApplicativeCtsL f g h a b\n  type ApplicativeCtsR (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) a b = ApplicativeCtsR f g h a b\n  (Generics.M1 mf) <*> (Generics.M1 ma) = Generics.M1 $ mf <*> ma\n  (Generics.M1 mf)  *> (Generics.M1 ma) = Generics.M1 $ mf  *> ma\n  (Generics.M1 mf) <*  (Generics.M1 ma) = Generics.M1 $ mf <*  ma\n#endif\n\n-- Constrained Instances -------------------------------------------------------\n\ninstance Applicative S.Set S.Set S.Set where\n  type ApplicativeCts S.Set S.Set S.Set a b = Ord b\n  type ApplicativeCtsR S.Set S.Set S.Set a b = ()\n  type ApplicativeCtsL S.Set S.Set S.Set a b = ()\n  fs  <*> as = S.foldr (\\f r -> S.map f as `S.union` r) S.empty fs\n  as  <*  _bs = as\n  _as *>  bs = bs\n\n-- \"transformers\" package instances: -------------------------------------------\n\n-- Continuations are so wierd...\n-- | TODO / FIXME: Still need to figure out how and if we can generalize the continuation implementation.\ninstance Applicative (Cont.ContT r m) (Cont.ContT r m) (Cont.ContT r m) where\n  type ApplicativeCts (Cont.ContT r m) (Cont.ContT r m) (Cont.ContT r m) a b = ()\n  f <*> a = Cont.ContT $ \\ c -> Cont.runContT f $ \\ g -> Cont.runContT a (c . g)\n  (<*) = defaultAppL\n  (*>) = defaultAppR\n  {-# INLINE (<*>) #-}\n\ninstance (Applicative m n p) => Applicative (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) where\n  type ApplicativeCts (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) a b = \n        ( ApplicativeCts m n p (Either e a) (Either e b)\n        , FunctorCts m (Either e (a -> b)) (Either e a -> Either e b) )\n  type ApplicativeCtsL (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) a b = \n        (ApplicativeCtsL m n p (Either e a) (Either e b))\n  type ApplicativeCtsR (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) a b = \n        (ApplicativeCtsR m n p (Either e a) (Either e b))\n  Except.ExceptT f <*> Except.ExceptT v = Except.ExceptT $ fmap (<*>) f <*> v\n  Except.ExceptT a <*  Except.ExceptT b = Except.ExceptT $ a <* b\n  Except.ExceptT a *>  Except.ExceptT b = Except.ExceptT $ a *> b\n  {-# INLINEABLE (<*>) #-}\n\ninstance (Applicative m n p) => Applicative (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) where\n  type ApplicativeCts  (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) a b = (ApplicativeCts m n p a b)\n  type ApplicativeCtsR (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) a b = (ApplicativeCtsR m n p a b)\n  type ApplicativeCtsL (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) a b = (ApplicativeCtsL m n p a b)\n  Identity.IdentityT m <*> Identity.IdentityT k = Identity.IdentityT $ m <*> k\n  Identity.IdentityT a <*  Identity.IdentityT b = Identity.IdentityT $ a <* b\n  Identity.IdentityT a *>  Identity.IdentityT b = Identity.IdentityT $ a *> b\n  {-# INLINE (<*>) #-}\n\ninstance (Applicative m n p) => Applicative (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) where\n  type ApplicativeCts  (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) a b = \n        ( ApplicativeCts m n p (Maybe a) (Maybe b)\n        , FunctorCts m (Maybe (a -> b)) (Maybe a -> Maybe b) )\n  type ApplicativeCtsR (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) a b = \n        ( ApplicativeCtsR m n p (Maybe a) (Maybe b) )\n  type ApplicativeCtsL (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) a b =\n        ( ApplicativeCtsL m n p (Maybe a) (Maybe b) )\n  Maybe.MaybeT f <*> Maybe.MaybeT x = Maybe.MaybeT $ fmap (<*>) f <*> x\n  Maybe.MaybeT a <*  Maybe.MaybeT b = Maybe.MaybeT $ a <* b\n  Maybe.MaybeT a *>  Maybe.MaybeT b = Maybe.MaybeT $ a *> b\n  {-# INLINE (<*>) #-}\n\ninstance (P.Monoid w, Bind m n p) => Applicative (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) where\n  type ApplicativeCts (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) a b = \n        ( BindCts m n p (a -> b, s, w) (b, s, w)\n        , FunctorCts n (a, s, w) (b, s, w) )\n  type ApplicativeCtsR (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) a b = \n        (DefaultAppCtsR (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) a b)\n  type ApplicativeCtsL (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) a b = \n        (DefaultAppCtsL (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) a b)\n  RWSL.RWST mf <*> RWSL.RWST ma  = RWSL.RWST $ \\r s -> mf r s >>= \\ ~(f, s', w) -> fmap (\\ ~(a, s'', w') -> (f a, s'', P.mappend w w')) (ma r s')\n  (<*) = defaultAppL\n  (*>) = defaultAppR\n  {-# INLINE (<*>) #-}\n\ninstance (P.Monoid w, Bind m n p) => Applicative (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) where\n  type ApplicativeCts (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) a b = \n        ( BindCts m n p (a -> b, s, w) (b, s, w)\n        , FunctorCts n (a, s, w) (b, s, w) )\n  type ApplicativeCtsR (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) a b = \n        (DefaultAppCtsR (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) a b)\n  type ApplicativeCtsL (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) a b = \n        (DefaultAppCtsL (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) a b)\n  RWSS.RWST mf <*> RWSS.RWST ma = RWSS.RWST $ \\r s -> mf r s >>= \\ (f, s', w) -> fmap (\\ (a, s'', w') -> (f a, s'', P.mappend w w')) (ma r s')\n  (<*) = defaultAppL\n  (*>) = defaultAppR\n  {-# INLINE (<*>) #-}\n\ninstance (Applicative m n p) => Applicative (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) where\n  type ApplicativeCts (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) a b = (ApplicativeCts m n p a b)\n  type ApplicativeCtsR (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) a b = \n        (DefaultAppCtsR (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) a b)\n  type ApplicativeCtsL (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) a b = \n        (DefaultAppCtsL (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) a b)\n  Reader.ReaderT mf <*> Reader.ReaderT ma  = Reader.ReaderT $ \\r -> mf r <*> ma r\n  (<*) = defaultAppL\n  (*>) = defaultAppR\n  {-# INLINE (<*>) #-}\n\ninstance (Bind m n p) => Applicative (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) where\n  type ApplicativeCts (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) a b = \n        ( BindCts m n p (a -> b, s) (b, s)\n        , FunctorCts n (a, s) (b, s) )\n  type ApplicativeCtsR (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) a b = \n        (DefaultAppCtsR (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) a b)\n  type ApplicativeCtsL (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) a b = \n        (DefaultAppCtsL (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) a b)\n  StateL.StateT mf <*> StateL.StateT ma = StateL.StateT $ \\s -> mf s >>= \\ ~(f, s') -> fmap (\\ ~(a, s'') -> (f a, s'')) (ma s')\n  (<*) = defaultAppL\n  (*>) = defaultAppR\n  {-# INLINE (<*>) #-}\n\ninstance (Bind m n p) => Applicative (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) where\n  type ApplicativeCts (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) a b = \n        ( BindCts m n p (a -> b, s) (b, s)\n        , FunctorCts n (a, s) (b, s) )\n  type ApplicativeCtsR (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) a b = \n        (DefaultAppCtsR (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) a b)\n  type ApplicativeCtsL (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) a b = \n        (DefaultAppCtsL (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) a b)\n  StateS.StateT mf <*> StateS.StateT ma = StateS.StateT $ \\s -> mf s >>= \\ (f, s') -> fmap (\\ (a, s'') -> (f a, s'')) (ma s')\n  (<*) = defaultAppL\n  (*>) = defaultAppR\n  {-# INLINE (<*>) #-}\n\ninstance (P.Monoid w, Applicative m n p) => Applicative (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) where\n  type ApplicativeCts (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) a b = \n        ( ApplicativeCts m n p (a, w) (b, w)\n        , FunctorCts m (a -> b, w) ((a, w) -> (b, w)) )\n  type ApplicativeCtsR (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) a b = \n        (DefaultAppCtsR (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) a b)\n  type ApplicativeCtsL (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) a b = \n        (DefaultAppCtsL (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) a b)\n  WriterL.WriterT mf <*> WriterL.WriterT ma = WriterL.WriterT $ fmap (\\ ~(f, w) ~(a, w') -> (f a, P.mappend w w')) mf <*> ma\n  (<*) = defaultAppL\n  (*>) = defaultAppR\n  {-# INLINE (<*>) #-}\n\ninstance (P.Monoid w, Applicative m n p) => Applicative (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) where\n  type ApplicativeCts (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) a b = \n        ( ApplicativeCts m n p (a, w) (b, w)\n        , FunctorCts m (a -> b, w) ((a, w) -> (b, w)) )\n  type ApplicativeCtsR (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) a b = \n        (DefaultAppCtsR (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) a b)\n  type ApplicativeCtsL (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) a b = \n        (DefaultAppCtsL (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) a b)\n  WriterS.WriterT mf <*> WriterS.WriterT ma = WriterS.WriterT $ fmap (\\ (f, w) (a, w') -> (f a, P.mappend w w')) mf <*> ma\n  (<*) = defaultAppL\n  (*>) = defaultAppR\n  {-# INLINE (<*>) #-}\n  \n-- -----------------------------------------------------------------------------\n-- Supermonad Type Class\n-- -----------------------------------------------------------------------------\n\ninfixl 1  >>, >>=\n\n-- | See @Control.Supermonad.@'Control.Supermonad.Bind' for details on laws and requirements.\nclass (Functor m, Functor n, Functor p) => Bind m n p where\n  type BindCts m n p (a :: *) (b :: *) :: Constraint\n  type BindCts m n p a b = ()\n  (>>=) :: (BindCts m n p a b) => m a -> (a -> n b) -> p b\n  (>>)  :: (BindCts m n p a b) => m a -> n b -> p b\n  ma >> mb = ma >>= const mb\n\ninstance Bind ((->) r) ((->) r) ((->) r) where\n  (>>=) = (P.>>=)\ninstance Bind Identity Identity Identity where\n  (>>=) = (P.>>=)\ninstance Bind [] [] [] where\n  (>>=) = (P.>>=)\ninstance Bind P.Maybe P.Maybe P.Maybe where\n  (>>=) = (P.>>=)\ninstance Bind P.IO P.IO P.IO where\n  (>>=) = (P.>>=)\ninstance Bind (P.Either e) (P.Either e) (P.Either e) where\n  (>>=) = (P.>>=)\n\ninstance Bind Mon.First Mon.First Mon.First where\n  (>>=) = (P.>>=)\ninstance Bind Mon.Last Mon.Last Mon.Last where\n  (>>=) = (P.>>=)\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Bind Mon.Sum Mon.Sum Mon.Sum where\n  (>>=) = (P.>>=)\ninstance Bind Mon.Product Mon.Product Mon.Product where\n  (>>=) = (P.>>=)\ninstance Bind Mon.Dual Mon.Dual Mon.Dual where\n  (>>=) = (P.>>=)\n#endif\ninstance (Bind f g h) => Bind (Mon.Alt f) (Mon.Alt g) (Mon.Alt h) where\n  type BindCts (Mon.Alt f) (Mon.Alt g) (Mon.Alt h) a b = BindCts f g h a b\n  (Mon.Alt m) >>= f = Mon.Alt $ m >>= (Mon.getAlt . f)\n\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Bind Semigroup.Min Semigroup.Min Semigroup.Min where\n  (>>=) = (P.>>=)\ninstance Bind Semigroup.Max Semigroup.Max Semigroup.Max where\n  (>>=) = (P.>>=)\ninstance Bind Semigroup.Option Semigroup.Option Semigroup.Option where\n  (>>=) = (P.>>=)\ninstance Bind Semigroup.First Semigroup.First Semigroup.First where\n  (>>=) = (P.>>=)\ninstance Bind Semigroup.Last Semigroup.Last Semigroup.Last where\n  (>>=) = (P.>>=)\n#endif\n\ninstance Bind Proxy.Proxy Proxy.Proxy Proxy.Proxy where\n  (>>=) = (P.>>=)\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Bind Complex.Complex Complex.Complex Complex.Complex where\n  (>>=) = (P.>>=)\ninstance Bind NonEmpty.NonEmpty NonEmpty.NonEmpty NonEmpty.NonEmpty where\n  (>>=) = (P.>>=)\n#endif\ninstance (Bind m1 n1 p1, Bind m2 n2 p2) => Bind (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) where\n  type BindCts (Product.Product m1 m2) (Product.Product n1 n2) (Product.Product p1 p2) a b = (BindCts m1 n1 p1 a b, BindCts m2 n2 p2 a b)\n  Product.Pair m1 m2 >>= f = Product.Pair (m1 >>= (fstP . f)) (m2 >>= (sndP . f))\n    where fstP (Product.Pair a _) = a\n          sndP (Product.Pair _ b) = b\n\ninstance Bind Read.ReadP Read.ReadP Read.ReadP where\n  (>>=) = (P.>>=)\ninstance Bind Read.ReadPrec Read.ReadPrec Read.ReadPrec where\n  (>>=) = (P.>>=)\n\ninstance Bind (ST.ST s) (ST.ST s) (ST.ST s) where\n  (>>=) = (P.>>=)\ninstance Bind (STL.ST s) (STL.ST s) (STL.ST s) where\n  (>>=) = (P.>>=)\ninstance (Arrow.ArrowApply a) => Bind (Arrow.ArrowMonad a) (Arrow.ArrowMonad a) (Arrow.ArrowMonad a) where\n  (>>=) = (P.>>=)\ninstance (Bind m n p) => Bind (App.WrappedMonad m) (App.WrappedMonad n) (App.WrappedMonad p) where\n  type BindCts (App.WrappedMonad m) (App.WrappedMonad n) (App.WrappedMonad p) a b = BindCts m n p a b\n  m >>= f = App.WrapMonad $ (App.unwrapMonad m) >>= (App.unwrapMonad . f)\n\ninstance Bind STM.STM STM.STM STM.STM where\n  (>>=) = (P.>>=)\n\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Bind Generics.U1 Generics.U1 Generics.U1 where\n  (>>=) = (P.>>=)\ninstance (Bind m n p) => Bind (Generics.Rec1 m) (Generics.Rec1 n) (Generics.Rec1 p) where\n  type BindCts (Generics.Rec1 m) (Generics.Rec1 n) (Generics.Rec1 p) a b = BindCts m n p a b\n  (Generics.Rec1 mf) >>= f = Generics.Rec1 $ mf >>= (Generics.unRec1 . f)\ninstance (Bind f g h, Bind f' g' h') => Bind (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') where\n  type BindCts (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') a b = (BindCts f g h a b, BindCts f' g' h' a b)\n  (f Generics.:*: g) >>= m = (f >>= \\a -> let (f' Generics.:*: _g') = m a in f') Generics.:*: (g >>= \\a -> let (_f' Generics.:*: g') = m a in g')\ninstance Bind f g h => Bind (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) where\n  type BindCts  (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) a b = BindCts  f g h a b\n  (Generics.M1 ma) >>= f = Generics.M1 $ ma >>= Generics.unM1 . f\n#endif\n\n-- Constrained Instances -------------------------------------------------------\n\ninstance Bind S.Set S.Set S.Set where\n  type BindCts S.Set S.Set S.Set a b = Ord b\n  s >>= f = S.foldr S.union S.empty $ S.map f s\n\n\n-- \"transformers\" package instances: -------------------------------------------\n\n-- Continuations are so wierd...\n-- | TODO / FIXME: Still need to figure out how and if we can generalize the continuation implementation.\ninstance {- (Bind m n p) => -} Bind (Cont.ContT r m) (Cont.ContT r m) (Cont.ContT r m) where\n  type BindCts (Cont.ContT r m) (Cont.ContT r m) (Cont.ContT r m) a b = () -- (BindCts m n p)\n  m >>= k = Cont.ContT $ \\ c -> Cont.runContT m (\\ x -> Cont.runContT (k x) c)\n  {-# INLINE (>>=) #-}\n\ninstance (Bind m n p, Return n) => Bind (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) where\n  type BindCts (Except.ExceptT e m) (Except.ExceptT e n) (Except.ExceptT e p) a b = (BindCts m n p (P.Either e a) (P.Either e b), ReturnCts n (P.Either e b))\n  m >>= k = Except.ExceptT $ \n      Except.runExceptT m >>= \n      \\ a -> case a of\n          P.Left e -> return (P.Left e)\n          P.Right x -> Except.runExceptT (k x)\n  {-# INLINE (>>=) #-}\n\ninstance (Bind m n p) => Bind (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) where\n  type BindCts (Identity.IdentityT m) (Identity.IdentityT n) (Identity.IdentityT p) a b = (BindCts m n p a b)\n  m >>= k = Identity.IdentityT $ Identity.runIdentityT m >>= (Identity.runIdentityT . k) \n  {-# INLINE (>>=) #-}\n\ninstance (Return n, Bind m n p) => Bind (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) where\n  type BindCts (Maybe.MaybeT m) (Maybe.MaybeT n) (Maybe.MaybeT p) a b = (ReturnCts n (P.Maybe b), BindCts m n p (P.Maybe a) (P.Maybe b))\n  x >>= f = Maybe.MaybeT $\n    Maybe.runMaybeT x >>=\n    \\v -> case v of\n      P.Nothing -> return P.Nothing\n      P.Just y  -> Maybe.runMaybeT (f y)\n  {-# INLINE (>>=) #-}\n\ninstance (P.Monoid w, Bind m n p) => Bind (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) where\n  type BindCts (RWSL.RWST r w s m) (RWSL.RWST r w s n) (RWSL.RWST r w s p) a b = (BindCts m n p (a, s, w) (b, s, w), FunctorCts n (b, s, w) (b, s, w))\n  m >>= k  = RWSL.RWST $ \n    \\ r s -> RWSL.runRWST m r s >>=\n    \\ ~(a, s', w) -> fmap (\\ ~(b, s'',w') -> (b, s'', w `P.mappend` w')) $ RWSL.runRWST (k a) r s'\n  {-# INLINE (>>=) #-}\n\ninstance (P.Monoid w, Bind m n p) => Bind (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) where\n  type BindCts (RWSS.RWST r w s m) (RWSS.RWST r w s n) (RWSS.RWST r w s p) a b = (BindCts m n p (a, s, w) (b, s, w), FunctorCts n (b, s, w) (b, s, w))\n  m >>= k  = RWSS.RWST $ \n    \\ r s -> RWSS.runRWST m r s >>=\n    \\ (a, s', w) -> fmap (\\(b, s'',w') -> (b, s'', w `P.mappend` w')) $ RWSS.runRWST (k a) r s'\n  {-# INLINE (>>=) #-}\n\ninstance (Bind m n p) => Bind (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) where\n  type BindCts (Reader.ReaderT r m) (Reader.ReaderT r n) (Reader.ReaderT r p) a b = (BindCts m n p a b)\n  m >>= k  = Reader.ReaderT $ \n      \\ r -> Reader.runReaderT m r >>=\n      \\ a -> Reader.runReaderT (k a) r\n  {-# INLINE (>>=) #-}\n\ninstance (Bind m n p) => Bind (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) where\n  type BindCts (StateL.StateT s m) (StateL.StateT s n) (StateL.StateT s p) a b = (BindCts m n p (a, s) (b, s))\n  m >>= k = StateL.StateT \n          $ \\ s -> StateL.runStateT m s >>= \n            \\ ~(a, s') -> StateL.runStateT (k a) s'\n  {-# INLINE (>>=) #-}\n\ninstance (Bind m n p) => Bind (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) where\n  type BindCts (StateS.StateT s m) (StateS.StateT s n) (StateS.StateT s p) a b = (BindCts m n p (a, s) (b, s))\n  m >>= k = StateS.StateT \n          $ \\ s -> StateS.runStateT m s >>= \n            \\ (a, s') -> StateS.runStateT (k a) s'\n  {-# INLINE (>>=) #-}\n\ninstance (P.Monoid w, Bind m n p) => Bind (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) where\n  type BindCts (WriterL.WriterT w m) (WriterL.WriterT w n) (WriterL.WriterT w p) a b = (BindCts m n p (a, w) (b, w), FunctorCts n (b, w) (b, w))\n  m >>= k  = WriterL.WriterT $\n      WriterL.runWriterT m >>=\n      \\ ~(a, w) -> fmap (\\ ~(b, w') -> (b, w `P.mappend` w')) $ WriterL.runWriterT (k a)\n  {-# INLINE (>>=) #-}\n\ninstance (P.Monoid w, Bind m n p) => Bind (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) where\n  type BindCts (WriterS.WriterT w m) (WriterS.WriterT w n) (WriterS.WriterT w p) a b = (BindCts m n p (a, w) (b, w), FunctorCts n (b, w) (b, w))\n  m >>= k  = WriterS.WriterT $\n      WriterS.runWriterT m >>=\n      \\ (a, w) -> fmap (\\ (b, w') -> (b, w `P.mappend` w')) $ WriterS.runWriterT (k a)\n  {-# INLINE (>>=) #-}\n\n-- -----------------------------------------------------------------------------\n-- Return Type Class\n-- -----------------------------------------------------------------------------\n\n-- | See 'Bind' for details on laws and requirements.\nclass (Functor m) => Return m where\n  type ReturnCts m (a :: *) :: Constraint\n  type ReturnCts m a = ()\n  return :: (ReturnCts m a) => a -> m a\n\ninstance Return ((->) r) where\n  return = P.return\ninstance Return Identity where\n  return = P.return\ninstance Return [] where\n  return = P.return\ninstance Return P.Maybe where\n  return = P.return\ninstance Return P.IO where\n  return = P.return\ninstance Return (P.Either e) where\n  return = P.return\n\ninstance Return Mon.First where\n  return = P.return\ninstance Return Mon.Last where\n  return = P.return\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Return Mon.Sum where\n  return = P.return\ninstance Return Mon.Product where\n  return = P.return\ninstance Return Mon.Dual where\n  return = P.return\n#endif\ninstance (Return m) => Return (Mon.Alt m) where\n  type ReturnCts (Mon.Alt m) a = ReturnCts m a\n  return a = Mon.Alt $ return a\n\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Return Semigroup.Min where\n  return = P.return\ninstance Return Semigroup.Max where\n  return = P.return\ninstance Return Semigroup.Option where\n  return = P.return\ninstance Return Semigroup.First where\n  return = P.return\ninstance Return Semigroup.Last where\n  return = P.return\n#endif\n\ninstance Return Proxy.Proxy where\n  return = P.return\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Return Complex.Complex where\n  return = P.return\ninstance Return NonEmpty.NonEmpty where\n  return = P.return\n#endif\n\ninstance (Return m1, Return m2) => Return (Product.Product m1 m2) where\n  type ReturnCts (Product.Product m1 m2) a = (ReturnCts m1 a, ReturnCts m2 a)\n  return a = Product.Pair (return a) (return a)\n\ninstance (Return f, Return f') => Return (Compose.Compose f f') where\n  type ReturnCts (Compose.Compose f f') a = (ReturnCts f (f' a), ReturnCts f' a)\n  return = Compose.Compose . return . return\n\ninstance Return Read.ReadP where\n  return = P.return\ninstance Return Read.ReadPrec where\n  return = P.return\n\ninstance Return (ST.ST s) where\n  return = P.return\ninstance Return (STL.ST s) where\n  return = P.return\ninstance (Arrow.ArrowApply a) => Return (Arrow.ArrowMonad a) where\n  return = P.return\ninstance (Return m) => Return (App.WrappedMonad m) where\n  type ReturnCts (App.WrappedMonad m) a = ReturnCts m a\n  return a = App.WrapMonad $ return a\n\ninstance Return STM.STM where\n  return = P.return\n\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Return Generics.U1 where\n  return = P.return\ninstance (Return m) => Return (Generics.Rec1 m) where\n  type ReturnCts (Generics.Rec1 m) a = ReturnCts m a\n  return = Generics.Rec1 . return\ninstance (Return f, Return g) => Return (f Generics.:*: g) where\n  type ReturnCts (f Generics.:*: g) a = (ReturnCts f a, ReturnCts g a)\n  return a = return a Generics.:*: return a\ninstance (Return f, Return g) => Return (f Generics.:.: g) where\n  type ReturnCts (f Generics.:.: g) a = (ReturnCts f (g a), ReturnCts g a)\n  return a = Generics.Comp1 $ return (return a)\ninstance Return f => Return (Generics.M1 i c f) where\n  type ReturnCts (Generics.M1 i c f) a = ReturnCts f a\n  return = Generics.M1 . return\n#endif\n\n-- Constrained Instances -------------------------------------------------------\n\ninstance Return S.Set where\n  return = S.singleton\n\n-- \"transformers\" package instances: -------------------------------------------\n\n-- Continuations are so weird...\ninstance {- (Return m) => -} Return (Cont.ContT r m) where\n  type ReturnCts (Cont.ContT r m) a = () -- ReturnCts m\n  return x = Cont.ContT ($ x)\n  {-# INLINE return #-}\n\ninstance (Return m) => Return (Except.ExceptT e m) where\n  type ReturnCts (Except.ExceptT e m) a = ReturnCts m (P.Either e a)\n  return = Except.ExceptT . return . P.Right\n  {-# INLINE return #-}\n\ninstance (Return m) => Return (Identity.IdentityT m) where\n  type ReturnCts (Identity.IdentityT m) a = ReturnCts m a\n  return = (Identity.IdentityT) . return\n  {-# INLINE return #-}\n\ninstance (Return m) => Return (Maybe.MaybeT m) where\n  type ReturnCts (Maybe.MaybeT m) a = ReturnCts m (P.Maybe a)\n  return = Maybe.MaybeT . return . P.Just\n  {-# INLINE return #-}\n\ninstance (P.Monoid w, Return m) => Return (RWSL.RWST r w s m) where\n  type ReturnCts (RWSL.RWST r w s m) a = ReturnCts m (a, s, w)\n  return a = RWSL.RWST $ \\ _ s -> return (a, s, P.mempty)\n  {-# INLINE return #-}\n\ninstance (P.Monoid w, Return m) => Return (RWSS.RWST r w s m) where\n  type ReturnCts (RWSS.RWST r w s m) a = ReturnCts m (a, s, w)\n  return a = RWSS.RWST $ \\ _ s -> return (a, s, P.mempty)\n  {-# INLINE return #-}\n\ninstance (Return m) => Return (Reader.ReaderT r m) where\n  type ReturnCts (Reader.ReaderT r m) a = ReturnCts m a\n  return = Reader.ReaderT . const . return\n  {-# INLINE return #-}\n\ninstance (Return m) => Return (StateL.StateT s m) where\n  type ReturnCts (StateL.StateT s m) a = ReturnCts m (a, s)\n  return x = StateL.StateT $ \\s -> return (x, s)\n  {-# INLINE return #-}\n\ninstance (Return m) => Return (StateS.StateT s m) where\n  type ReturnCts (StateS.StateT s m) a = ReturnCts m (a, s)\n  return x = StateS.StateT $ \\s -> return (x, s)\n  {-# INLINE return #-}\n\ninstance (P.Monoid w, Return m) => Return (WriterL.WriterT w m) where\n  type ReturnCts (WriterL.WriterT w m) a = ReturnCts m (a, w)\n  return a = WriterL.WriterT $ return (a, P.mempty)\n  {-# INLINE return #-}\n\ninstance (P.Monoid w, Return m) => Return (WriterS.WriterT w m) where\n  type ReturnCts (WriterS.WriterT w m) a = ReturnCts m (a, w)\n  return a = WriterS.WriterT $ return (a, P.mempty)\n  {-# INLINE return #-}\n\n-- -----------------------------------------------------------------------------\n-- Fail Type Class\n-- -----------------------------------------------------------------------------\n\n-- | See 'Bind' for details on laws and requirements.\nclass Fail m where\n  type FailCts m (a :: *) :: Constraint\n  type FailCts m a = ()\n  fail :: (FailCts m a) => String -> m a\n\ninstance Fail ((->) r) where\n  fail = P.fail\ninstance Fail Identity where\n  fail = P.fail\ninstance Fail [] where\n  fail = P.fail\ninstance Fail P.Maybe where\n  fail = P.fail\ninstance Fail P.IO where\n  fail = P.fail\ninstance Fail (P.Either e) where\n  fail = P.fail\n\ninstance Fail Mon.First where\n  fail = P.fail\ninstance Fail Mon.Last where\n  fail = P.fail\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Fail Mon.Sum where\n  fail = P.fail\ninstance Fail Mon.Product where\n  fail = P.fail\ninstance Fail Mon.Dual where\n  fail = P.fail\n#endif\ninstance (Fail m) => Fail (Mon.Alt m) where\n  type FailCts (Mon.Alt m) a = FailCts m a\n  fail a = Mon.Alt $ fail a\n\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Fail Semigroup.Min where\n  fail = P.fail\ninstance Fail Semigroup.Max where\n  fail = P.fail\ninstance Fail Semigroup.Option where\n  fail = P.fail\ninstance Fail Semigroup.First where\n  fail = P.fail\ninstance Fail Semigroup.Last where\n  fail = P.fail\n#endif\n\ninstance Fail Proxy.Proxy where\n  fail = P.fail\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Fail Complex.Complex where\n  fail = P.fail\ninstance Fail NonEmpty.NonEmpty where\n  fail = P.fail\n#endif\ninstance (Fail m1, Fail m2) => Fail (Product.Product m1 m2) where\n  type FailCts (Product.Product m1 m2) a = (FailCts m1 a, FailCts m2 a)\n  fail a = Product.Pair (fail a) (fail a)\n\ninstance Fail Read.ReadP where\n  fail = P.fail\ninstance Fail Read.ReadPrec where\n  fail = P.fail\n\ninstance Fail (ST.ST s) where\n  fail = P.fail\ninstance Fail (STL.ST s) where\n  fail = P.fail\ninstance (Arrow.ArrowApply a) => Fail (Arrow.ArrowMonad a) where\n  fail = P.fail\ninstance (Fail m) => Fail (App.WrappedMonad m) where\n  type FailCts (App.WrappedMonad m) a = FailCts m a\n  fail a = App.WrapMonad $ fail a\n\ninstance Fail STM.STM where\n  fail = P.fail\n\n#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)\ninstance Fail Generics.U1 where\n  fail = P.fail\ninstance (Fail m) => Fail (Generics.Rec1 m) where\n  type FailCts (Generics.Rec1 m) a = FailCts m a\n  fail = Generics.Rec1 . fail\ninstance (Fail f, Fail g) => Fail (f Generics.:*: g) where\n  type FailCts (f Generics.:*: g) a = (FailCts f a, FailCts g a)\n  fail a = fail a Generics.:*: fail a\ninstance Fail f => Fail (Generics.M1 i c f) where\n  type FailCts (Generics.M1 i c f) a = FailCts f a\n  fail = Generics.M1 . fail\n#endif\n\n-- Constrained Instances -------------------------------------------------------\n\ninstance Fail S.Set where\n  fail _ = S.empty\n\n-- \"transformers\" package instances: -------------------------------------------\n\ninstance (Fail m) => Fail (Cont.ContT r m) where\n  type FailCts (Cont.ContT r m) a = (FailCts m r)\n  fail = (Cont.ContT) . const . fail\n  {-# INLINE fail #-}\n\n-- Requires 'UndecidableInstances'.\ninstance (Fail m) => Fail (Except.ExceptT e m) where\n  type FailCts (Except.ExceptT e m) a = (FailCts m (P.Either e a))\n  fail = Except.ExceptT . fail\n  {-# INLINE fail #-}\n\ninstance (Fail m) => Fail (Identity.IdentityT m) where\n  type FailCts (Identity.IdentityT m) a = (FailCts m a)\n  fail msg = Identity.IdentityT $ fail msg\n  {-# INLINE fail #-}\n\n-- Requires 'UndecidableInstances'.\ninstance (Return m) => Fail (Maybe.MaybeT m) where\n  type FailCts (Maybe.MaybeT m) a = (ReturnCts m (P.Maybe a))\n  fail _ = Maybe.MaybeT (return P.Nothing)\n  {-# INLINE fail #-}\n\ninstance (P.Monoid w, Fail m) => Fail (RWSL.RWST r w s m) where\n  type FailCts (RWSL.RWST r w s m) a = (FailCts m (a, s, w))\n  fail msg = RWSL.RWST $ \\ _ _ -> fail msg\n  {-# INLINE fail #-}\n\ninstance (P.Monoid w, Fail m) => Fail (RWSS.RWST r w s m) where\n  type FailCts (RWSS.RWST r w s m) a = (FailCts m (a, s, w))\n  fail msg = RWSS.RWST $ \\ _ _ -> fail msg\n  {-# INLINE fail #-}\n\ninstance (Fail m) => Fail (Reader.ReaderT r m) where\n  type FailCts (Reader.ReaderT r m) a = (FailCts m a)\n  fail = Reader.ReaderT . const . fail\n  {-# INLINE fail #-}\n\n-- Requires 'UndecidableInstances'.\ninstance (Fail m) => Fail (StateL.StateT s m) where\n  type FailCts (StateL.StateT s m) a = (FailCts m (a, s))\n  fail = StateL.StateT . const . fail\n  {-# INLINE fail #-}\n\n-- Requires 'UndecidableInstances'.\ninstance (Fail m) => Fail (StateS.StateT s m) where\n  type FailCts (StateS.StateT s m) a = (FailCts m (a, s))\n  fail = StateS.StateT . const . fail\n  {-# INLINE fail #-}\n\n-- Requires 'UndecidableInstances'.\ninstance (P.Monoid w, Fail m) => Fail (WriterL.WriterT w m) where\n  type FailCts (WriterL.WriterT w m) a = (FailCts m (a, w))\n  fail msg = WriterL.WriterT $ fail msg\n  {-# INLINE fail #-}\n\n-- Requires 'UndecidableInstances'.\ninstance (P.Monoid w, Fail m) => Fail (WriterS.WriterT w m) where\n  type FailCts (WriterS.WriterT w m) a = (FailCts m (a, w))\n  fail msg = WriterS.WriterT $ fail msg\n  {-# INLINE fail #-}\n\n-- -----------------------------------------------------------------------------\n-- Convenient type synonyms\n-- -----------------------------------------------------------------------------\n\n-- | A short-hand for writing polymorphic standard monad functions.\ntype family Monad m :: Constraint where\n  Monad m = (Bind m m m, Return m, Fail m)\n\n\n\n", "meta": {"hexsha": "add9f938e2ed327339ced8854f7ab23c2b720805", "size": 44130, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Control/Super/Monad/Constrained.hs", "max_stars_repo_name": "jbracker/supermonad-plugin", "max_stars_repo_head_hexsha": "2595396a225a65b1dce6ed9a1ce59960f392a55b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 22, "max_stars_repo_stars_event_min_datetime": "2016-07-23T07:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T13:36:44.000Z", "max_issues_repo_path": "src/Control/Super/Monad/Constrained.hs", "max_issues_repo_name": "jbracker/supermonad", "max_issues_repo_head_hexsha": "2595396a225a65b1dce6ed9a1ce59960f392a55b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2016-12-25T16:50:49.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-17T06:11:56.000Z", "max_forks_repo_path": "src/Control/Super/Monad/Constrained.hs", "max_forks_repo_name": "jbracker/supermonad-plugin", "max_forks_repo_head_hexsha": "2595396a225a65b1dce6ed9a1ce59960f392a55b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-12-25T16:17:02.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-25T16:17:02.000Z", "avg_line_length": 44.1741741742, "max_line_length": 164, "alphanum_fraction": 0.604645366, "num_tokens": 14944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.18572181206653077}}
{"text": "module CreateTerrain\nwhere\n\nimport Data.Maybe\nimport Control.Monad.State\nimport System.Random\n\nimport Galaxy\nimport Math\nimport CreateGalaxy\nimport DataFunction\nimport Utils\nimport Statistics\nimport Good\nimport Terrain\n\nnearsystems :: [String]\nnearsystems = [\"Alpha Centauri\",\n               \"Barnard's Star\",\n               \"Wolf 359\",\n               \"Lalande 21185\",\n               \"Sirius\",\n               \"Lyuten 726-8\",\n               \"Ross 154\",\n               \"Ross 248\",\n               \"Epsilon Eridani\",\n               \"Lacaille 9352\",\n               \"Ross 128\",\n               \"EZ Aquarii\",\n               \"Procyon\",\n               \"61 Cygni\",\n               \"Tau Ceti\",\n               \"Fomalhaut\",\n               \"Struve 2398\",\n               \"Groombridge 34\",\n               \"Epsilon Indi\",\n               \"DX Cancri\",\n               \"GJ 1061\",\n               \"YZ Ceti\", \n               \"Lyuten's Star\",\n               \"Kapteyn's Star\"\n              ]\n\ntestGalaxy :: Galaxy Terrain\ntestGalaxy = testRandomGalaxy 20 16\n\ntestRandomGalaxy :: Int -> Int -> Galaxy Terrain\ntestRandomGalaxy v numsys =\n  let r = mkStdGen v\n  in evalState (createGalaxy (createTerrain stdGoods) \"milky way\" (take numsys $ nearsystems ++ map show [1..numsys])) r\n\ncreateTerrain :: [Good] -> Planet () -> Rnd Terrain\ncreateTerrain gs p = \n  case planettype p of\n    Planetoid         -> createRockyTerrain gs p\n    NoAtmosphere      -> createRockyTerrain gs p\n    RockyPlanet _     -> createRockyTerrain gs p\n    SmallGasGiant     -> return (Terrain [] [])\n    MediumGasGiant    -> return (Terrain [] [])\n    LargeGasGiant     -> return (Terrain [] [])\n    VeryLargeGasGiant -> return (Terrain [] [])\n\ncreateRockyTerrain :: [Good] -> Planet () -> Rnd Terrain\ncreateRockyTerrain gs p = do\n  massmult <- randomRM (0, 1000 * planetMass p)\n  gs' <- mapMaybeM (createNaturalGood massmult (planettype p)) gs\n  return (Terrain gs' [])\n\ncreateNaturalGood :: Flt -> PlanetType -> Good -> Rnd (Maybe (Resource, ResourceUnit))\ncreateNaturalGood massmult pt g = \n  case natural g of\n    Nothing                       -> return Nothing\n    Just (Natural atms _ initial) -> do\n      let atmNeeded = not $ null atms\n      let invAtm = if not atmNeeded \n                     then False\n                     else case pt of\n                       RockyPlanet a -> a `notElem` atms\n                       _             -> True\n      if invAtm \n        then return Nothing\n        else do\n          mult <- randomRM (0, initial)\n          let v = floor $ mult * massmult\n          return $ Just ((g, v), v)\n\n\n", "meta": {"hexsha": "da8fa6bbc66d6097ce49d4628f898d9f853ae989", "size": 2576, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/CreateTerrain.hs", "max_stars_repo_name": "anttisalonen/starrover", "max_stars_repo_head_hexsha": "b1b3ae4c4f559bc041b92a093fdeb7a72527de4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-28T13:41:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-28T13:41:07.000Z", "max_issues_repo_path": "src/CreateTerrain.hs", "max_issues_repo_name": "anttisalonen/starrover", "max_issues_repo_head_hexsha": "b1b3ae4c4f559bc041b92a093fdeb7a72527de4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CreateTerrain.hs", "max_forks_repo_name": "anttisalonen/starrover", "max_forks_repo_head_hexsha": "b1b3ae4c4f559bc041b92a093fdeb7a72527de4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2727272727, "max_line_length": 120, "alphanum_fraction": 0.5469720497, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.2974699363766585, "lm_q1q2_score": 0.1840685720744139}}
{"text": "module Fractal.Control.Controller(\n  ApplicationType (UI_Application, Console_Application),\n  mandelApplication,\n  getApplicationType\n)where\n\nimport  System.IO (BufferMode (NoBuffering), hSetBuffering, stdout)\nimport qualified Fractal.Parallel.Evaluator as P\nimport qualified Fractal.Gui.FractalWindow as W\nimport qualified Fractal.Utils.Field as F\nimport Fractal.Math.Mandelbrot (mandel, mandel')\nimport Data.Complex\nimport Fractal.Plot.Plotter (imageFractal)\nimport Data.DateTime\n\n\ndata ApplicationType = UI_Application | Console_Application | None | Empty\n  deriving (Show, Eq)\n\ntype Point = Complex Double\n\nmandelApplication :: ApplicationType -> IO ()\nmandelApplication appType = case appType of\n  UI_Application        -> uiApplication\n  Console_Application   -> consoleApplication\n  Empty                 -> readApplicationTypeFromInput\n  None                  -> error \"Cant use\"\n\ngetApplicationType :: [String] -> ApplicationType\ngetApplicationType [] = Empty\ngetApplicationType (x:_) = case x of\n  \"UI_Application\"      -> UI_Application\n  \"Console_Application\" -> Console_Application\n  _                     -> Empty\n\n\nreadApplicationTypeFromInput :: IO ()\nreadApplicationTypeFromInput = do\n  hSetBuffering stdout NoBuffering\n  putStr \"Provide application type (UI_Application or Console_Application): \"\n  applicationType <- getLine\n  let appType = getApplicationType [applicationType]\n  if appType == Empty then mandelApplication None else mandelApplication appType\n\nconsoleApplication :: IO ()\nconsoleApplication = do\n  putStrLn \"Running in console mode...\"\n  input <- consoleReadInput\n  coreComputation input\n  return ()\n\ncoreComputation :: (Double, Int, Double, Point, Point, String) -> IO ()\ncoreComputation (limit, maxIter, stepSize, sPoint, ePoint, strat) = do\n  --let field   = F.generateField sPoint ePoint stepSize\n  --let field'  = concat field\n  let field'  = F.generateRowField sPoint ePoint stepSize\n  let res     = P.mandelEval (P.stringToStrat strat) (mandel' maxIter limit) field'\n  let len     = F.getFieldLength sPoint ePoint stepSize\n  dateTime    <- getCurrentTime\n  let (year, month, day) = toGregorian' dateTime\n  imageFractal len res (\"./Mandel_\" ++ (show year) ++ \"_\" ++ (show month) ++ \"_\" ++ (show day) ++ \"_\" ++ (show $ toSeconds dateTime))\n  putStrLn \"Image created!\"\n  return ()\n\n\nuiApplication :: IO ()\nuiApplication = do\n  putStrLn \"Running in ui mode\"\n  W.mainW coreComputation\n  return ()\n\n\nconsoleReadInput :: IO (Double, Int, Double, Point, Point, String)\nconsoleReadInput = do\n  hSetBuffering stdout NoBuffering\n  putStr \"Type in recursive limit: \"\n  fractalLimit <- getLine\n  let limit = (read fractalLimit) :: Double\n  putStr \"Type in max number of iterations: \"\n  maxIter <- getLine\n  let maxIt = (read maxIter) :: Int\n  putStr \"Type in stepsize: \"\n  stepSize <- getLine\n  let step = (read stepSize) :: Double\n  putStr \"Type in starting point: \"\n  startPoint <- getLine\n  let startP = (read startPoint) :: Point\n  putStr \"Type in end point: \"\n  endPoint <- getLine\n  let endP = (read endPoint) :: Point\n  putStr \"Type in evaluation strategie: \"\n  evalStrat <- getLine\n  return (limit, maxIt, step, startP, endP, evalStrat)\n", "meta": {"hexsha": "4b6e9896bc8420b20db3e26ac08425bb6a945550", "size": 3174, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Fractal/Control/Controller.hs", "max_stars_repo_name": "sigmaticsMUC/FractalHaskell", "max_stars_repo_head_hexsha": "52782c63e67a06e21c0fbbe517faf86a3f1d48b6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Fractal/Control/Controller.hs", "max_issues_repo_name": "sigmaticsMUC/FractalHaskell", "max_issues_repo_head_hexsha": "52782c63e67a06e21c0fbbe517faf86a3f1d48b6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Fractal/Control/Controller.hs", "max_forks_repo_name": "sigmaticsMUC/FractalHaskell", "max_forks_repo_head_hexsha": "52782c63e67a06e21c0fbbe517faf86a3f1d48b6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7659574468, "max_line_length": 133, "alphanum_fraction": 0.724952741, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.18384633708869047}}
{"text": "-- This program is intentionally poorly documented; fixing the\n-- documentation and actually creating the program are left as exercises\n-- for the reader.\n\nimport qualified Data.List as DL;\nimport qualified Data.Function as DF;\nimport qualified Numeric.FFT as FT;\nimport Data.Complex;\n\n------------------------------------------------------------------------\n\nwindowSize :: Int;\nwindowSize = 65536;\n\n------------------------------------------------------------------------\n\ntype Giraffe = [(Int, Pitch)];  -- LIST OF GRAPH COORDINATES\ntype Pitch = Double;\ntype Sample = Double;\ntype Frequency = Double;\ntype Multiplier = Double;\ntype FFTOutput = [Complex Double];\ndata X11Winda = ExerciseForTheReader;\ndata WaveType = Sin | Cos;\n\n------------------------------------------------------------------------\n\n-- | createNewWinda creates a new X11 window and returns the tag of this\n-- X11 window.\ncreateNewWinda :: IO X11Winda;\ncreateNewWinda = return ExerciseForTheReader;\n\nfft :: [Sample] -> FFTOutput;\nfft = FT.fft . map cis;\n\n-- | For all FFT outputs k, fftToPitch equals the loudest pitch of k.\n-- Implementing fftToPitch is left as an exercise for the reader.\n-- Shut up and hack!\nfftToPitch :: FFTOutput -> Pitch;\nfftToPitch k = 0;\n\n-- | readMicData is a stream of microphone samples.\n-- Implementing readMicData is left as an exercise for the reader. \n-- The author recommends using the SDL library or an operating system-\n-- specific approach.\nreadMicData :: IO [Sample];\nreadMicData = return $ map (\\a -> a * (sin a)) [1.0,1.1..];\n\n-- | For all natural numbers n, readSamp n equals n microphone samples.\nreadSamp :: Int -> IO [Sample];\nreadSamp k = readMicData >>= return . take k;\n\n\n-- | For all [Sample] n, seqToPitch n equals the output of the sequence-\n-- to-pitch function on the input n.\nseqToPitch :: [Sample] -> Pitch;\nseqToPitch = fftToPitch . fft;\n\n-- | genCoords yields the coordinates of the graph.\ngenCoords :: [Pitch] -> Giraffe;\ngenCoords x = zip [0..length x - 1] x;\n\n-- | For all X11Winda k, for all Giraffe g, genGraph k g draws\n-- g to k, returning the pitch/y values of g.\n-- Implementing genGraph is left as an exercise for the reader.\n-- The author recommends using Chart or creating a custom library.\ngenGraph :: X11Winda -> Giraffe -> IO [Pitch];\ngenGraph w k = putStrLn \"TODO: IMPLEMENT GRAPHING.\" >> return (map snd k);\n\n-- | mane is the main program loop.\nmane :: X11Winda -> [Double] -> IO ();\nmane w k = readSamp windowSize >>= doTheGraph w >>= loop w\n  where\n  doTheGraph a b = genGraph a (genCoords $ append k $ seqToPitch b)\n  append a b = a ++ [b]\n  loop a b = mane a (take 50 b);\n\n-- | main is the program's entry point.  main initialises mane.\nmain :: IO ();\nmain = createNewWinda >>= \\winda -> mane winda [];\n", "meta": {"hexsha": "1e5a9042a67a826ea9247e38b0bc2b13c7ac307f", "size": 2750, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "pitchvst.hs", "max_stars_repo_name": "varikvalefor/tthheeppaarrttyy", "max_stars_repo_head_hexsha": "b10a833c32ddbc7c807423eb8af0d39629d42137", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pitchvst.hs", "max_issues_repo_name": "varikvalefor/tthheeppaarrttyy", "max_issues_repo_head_hexsha": "b10a833c32ddbc7c807423eb8af0d39629d42137", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pitchvst.hs", "max_forks_repo_name": "varikvalefor/tthheeppaarrttyy", "max_forks_repo_head_hexsha": "b10a833c32ddbc7c807423eb8af0d39629d42137", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.950617284, "max_line_length": 74, "alphanum_fraction": 0.6494545455, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.275129717879598, "lm_q1q2_score": 0.18211465409066108}}
{"text": "-----------------------------------------------------------------------------\n--\n-- Module      :  Drool.Utils.RenderHelpers\n-- Copyright   :  Tobias Fuchs\n-- License     :  AllRightsReserved\n--\n-- Maintainer  :  twh.fuchs@gmail.com\n-- Stability   :  experimental\n-- Portability :  POSIX\n--\n-- |\n--\n-----------------------------------------------------------------------------\n\n{-# OPTIONS -O2 -Wall #-}\n\nmodule Drool.Utils.RenderHelpers (\n    RenderSettings(..), \n    applyGlobalRotation, \n    applyPerspective, \n    nextPerspective, \n    useLight, \n    applyBandRangeAmp, \n    bandRangeAmpSamples, \n    scaleSamples, \n\n    vertexWithNormal, \n    vertexWithNormalAndColor, \n    normalsFromVertices, \n    drawNormal, \n    color3AddAlpha, \n    color4MulAlpha, \n    color3MulValue, \n    color4MulValue, \n\n    vertexToVector, \n    vx4ToVx3, \n\n    v3x, \n    v3y, \n    v3z, \n    vx3x, \n    vx3y, \n    vx3z, \n    vx4x, \n    vx4y, \n    vx4z, \n    vx4w, \n\n    getViewpointFromModelView, \n    featuresToIntensity\n) where\n\nimport Debug.Trace\n\n-- Imports\n-- {{{ \nimport Data.IORef ( IORef )\n\nimport Data.Packed.Matrix as HM ( (><), Matrix )\nimport Numeric.LinearAlgebra.Algorithms as LA ( inv ) \nimport Numeric.Container as NC ( vXm, fromList, toList )\n\nimport qualified Drool.Types as DT ( SignalList(..), RenderPerspective(..), RotationVector(..) )\nimport Drool.Utils.SigGen as SigGen ( SValue, TValue, SignalGenerator(..) )\nimport Drool.Utils.FeatureExtraction as FE ( \n    SignalFeatures(..), SignalFeaturesList(..), \n    emptyFeatures, \n    FeatureTarget(..), featureTargetFromIndex )\nimport Drool.Utils.Conversions as Conv ( interleaveArrays, aZip ) \nimport Drool.ApplicationContext as AC ( ContextSettings(..), LightConfig(..) )\nimport Graphics.Rendering.OpenGL ( \n    Vector3 (..), \n    Vertex3 (..), \n    Vertex4 (..), \n    Normal3 (..), \n    Color3(..),\n    Color4(..),\n    Light(..), \n    light, \n    VertexComponent,\n    renderPrimitive, \n    PrimitiveMode(..),\n    vertex, normal, \n    color, \n    materialEmission, \n    materialAmbient, \n    materialDiffuse, \n    materialSpecular,\n    materialShininess,\n    translate, \n    MatrixOrder(..), \n    getMatrixComponents, \n    GLmatrix, \n    ($=), \n    Face(..), \n    Capability(..),\n    polygonOffsetFill, \n    polygonOffsetLine, \n    ambient, \n    diffuse, \n    specular, \n    rotate, \n    translate, \n    GLfloat )\nimport qualified Graphics.Rendering.FTGL as FTGL\nimport qualified Control.Concurrent.MVar as MV ( MVar )\nimport qualified Control.Concurrent.Chan as CC\n-- }}}\n\n-- Settings rendering independent from visual used: \ndata RenderSettings = RenderSettings { signalGenerator :: SignalGenerator, \n                                       samplingSem :: MV.MVar Int, \n                                       renderingSem :: MV.MVar Int, \n                                       numNewSignalsChan :: CC.Chan Int, \n                                       -- IORef to signal buffer: \n                                       signalBuf :: IORef DT.SignalList, \n                                       -- Position of light 0\n                                       lightPos0 :: Vertex4 GLfloat, \n                                       -- Position of light 1\n                                       lightPos1 :: Vertex4 GLfloat, \n                                       -- Containing one SignalFeatures component for every signal: \n                                       featuresBuf :: IORef (FE.SignalFeaturesList), \n                                       -- Current number of signals in signal buffer: \n                                       numSignals :: Int, \n                                       -- Number of samples in most recent signal: \n                                       numSamples :: Int, \n                                       -- Number of new signals since last render pass: \n                                       numNewSignals :: Int, \n                                       -- Whether to reverse the signal buffer: \n                                       reverseBuffer :: Bool, \n                                       -- Tick of rendering pass: \n                                       tick :: Int }\n\napplyPerspective :: DT.RenderPerspective -> IO ()\napplyPerspective p = do\n  case p of\n    DT.Isometric -> do\n      rotate (45::GLfloat) $ Vector3 1.0 0.0 0.0\n      rotate (45::GLfloat) $ Vector3 0.0 1.0 0.0\n    DT.Top -> do\n      rotate (90::GLfloat) $ Vector3 1.0 0.0 0.0\n    DT.Front -> do\n      rotate (20.0::GLfloat) $ Vector3 1.0 0.0 0.0\n    DT.Side -> do\n      rotate (20.0::GLfloat) $ Vector3 1.0 0.0 0.0\n      rotate (-90::GLfloat) $ Vector3 0.0 1.0 0.0\n\napplyGlobalRotation :: DT.RotationVector -> DT.RotationVector -> IO ()\napplyGlobalRotation fixedRotation incRotation = do\n  rotate (DT.rotX fixedRotation) $ Vector3 1.0 0.0 0.0\n  rotate (DT.rotX incRotation)   $ Vector3 1.0 0.0 0.0\n  rotate (DT.rotY fixedRotation) $ Vector3 0.0 1.0 0.0\n  rotate (DT.rotY incRotation)   $ Vector3 0.0 1.0 0.0\n  rotate (DT.rotZ fixedRotation) $ Vector3 0.0 0.0 1.0\n  rotate (DT.rotZ incRotation)   $ Vector3 0.0 0.0 1.0\n\nnextPerspective :: DT.RenderPerspective -> DT.RenderPerspective\nnextPerspective cur = case cur of \n  DT.Isometric -> DT.Top\n  DT.Top       -> DT.Front \n  DT.Front     -> DT.Side\n  DT.Side      -> DT.Isometric\n\nuseLight :: AC.LightConfig -> IO ()\nuseLight lightConfig = do \n  let lightState = AC.lightState lightConfig\n  let lightIdx   = fromIntegral $ AC.lightIndex lightConfig\n  light (Light lightIdx) $= lightState\n  let lighting state = \n        if state == Enabled then do\n          let intensity = AC.lightIntensity lightConfig\n          ambient  (Light lightIdx) $= color4MulValue (AC.lightAmbient  lightConfig) intensity\n          diffuse  (Light lightIdx) $= color4MulValue (AC.lightDiffuse  lightConfig) intensity\n          specular (Light lightIdx) $= color4MulValue (AC.lightSpecular lightConfig) intensity\n        else\n          return ()\n  lighting lightState\n\n-- Expects a sample, t, number of samples in total, list of band range amplifiers, and returns amplified sample for t. \napplyBandRangeAmp :: SValue -> TValue -> Int -> [Float] -> SValue\n-- {{{\napplyBandRangeAmp s t nSamples amps = s * ampValue\n  where numRanges      = length amps\n        rangeWidth     = nSamples `div` numRanges                            -- ...[-------]...\n        rangePos       = t `mod` rangeWidth                                  -- ...|....x..|...\n        activeRangeIdx = max 0 $ ((fromIntegral t)-rangePos) `div` rangeWidth :: Int -- [.|x|.|.|.]\n        -- Amp value of active range\n        amp_1          = if length amps > activeRangeIdx then realToFrac $ amps !! activeRangeIdx else 1.0\n        -- Amp value of next range, use range n as next range of range n\n        nextRangeIdx   = max 0 $ min (activeRangeIdx+1) (numRanges-1) \n        amp_2          = if length amps > nextRangeIdx then realToFrac $ amps !! nextRangeIdx else 1.0\n        ampValue       = amp_1 + ((amp_2-amp_1) * (fromIntegral (rangePos) / fromIntegral (rangeWidth-1)))\n-- }}}\n\nbandRangeAmpSamples :: [SValue] -> [Float] -> [SValue]\nbandRangeAmpSamples samples amps = bandRangeAmpSamplesRec samples amps (length samples) 0\n\nbandRangeAmpSamplesRec :: [SValue] -> [Float] -> Int -> TValue -> [SValue]\nbandRangeAmpSamplesRec (x:xs) amps nSamples t = ampSample : (bandRangeAmpSamplesRec xs amps nSamples (t+1))\n  where ampSample = (applyBandRangeAmp x t nSamples amps)\nbandRangeAmpSamplesRec [] _ _ _ = []\n\nscaleSamples :: (Fractional a) => [a] -> a -> [a]\nscaleSamples samples a = map ( \\s -> s * a ) samples\n\n-- {{{\n\n-- Resolve x component of a 3-dimensional Vector\nv3x :: Vector3 a -> a\nv3x (Vector3 x _ _) = x\n-- Resolve y component of a 3-dimensional Vector\nv3y :: Vector3 a -> a\nv3y (Vector3 _ y _) = y\n-- Resolve z component of a 3-dimensional Vector\nv3z :: Vector3 a -> a\nv3z (Vector3 _ _ z) = z\n\n-- Resolve x component of a 3-dimensional Vertex\nvx3x :: Vertex3 a -> a\nvx3x (Vertex3 x _ _) = x\n-- Resolve y component of a 3-dimensional Vertex\nvx3y :: Vertex3 a -> a\nvx3y (Vertex3 _ y _) = y\n-- Resolve z component of a 3-dimensional Vertex\nvx3z :: Vertex3 a -> a\nvx3z (Vertex3 _ _ z) = z\n\n-- Resolve x component of a 4-dimensional Vertex\nvx4x :: Vertex4 a -> a\nvx4x (Vertex4 x _ _ _) = x\n-- Resolve y component of a 4-dimensional Vertex\nvx4y :: Vertex4 a -> a\nvx4y (Vertex4 _ y _ _) = y\n-- Resolve z component of a 4-dimensional Vertex\nvx4z :: Vertex4 a -> a\nvx4z (Vertex4 _ _ z _) = z\n-- Resolve w component of a 4-dimensional Vertex\nvx4w :: Vertex4 a -> a\nvx4w (Vertex4 _ _ _ w) = w\n\n-- Resolve x component of a 3-dimensional Normal\nn3x :: Normal3 a -> a\nn3x (Normal3 x _ _) = x\n-- Resolve y component of a 3-dimensional Normal\nn3y :: Normal3 a -> a\nn3y (Normal3 _ y _) = y\n-- Resolve z component of a 3-dimensional Normal\nn3z :: Normal3 a -> a\nn3z (Normal3 _ _ z) = z\n\n-- TODO: All these vector / matrix operations should be \n--       outsourced to BLAS. \n\nvx4ToVx3 :: Vertex4 a -> Vertex3 a\nvx4ToVx3 (Vertex4 x y z _) = Vertex3 x y z\n\nvertexToVector :: (Num a) => Vertex3 a -> Vector3 a \nvertexToVector v = Vector3 (vx3x v) (vx3y v) (vx3z v)\n\n-- Cross product of two vectors\nv3cross :: (Num a) => Vector3 a -> Vector3 a -> Vector3 a\nv3cross (Vector3 a1 a2 a3) (Vector3 b1 b2 b3) = Vector3 c1 c2 c3\n  where c1 = a2 * b3 - a3 * b2\n        c2 = a3 * b1 - a1 * b3\n        c3 = a1 * b2 - a2 * b1\n\nv3add :: (Num a) => Vector3 a -> Vector3 a -> Vector3 a\nv3add a b = Vector3 x y z\n  where x = v3x a + v3x b\n        y = v3y a + v3y b\n        z = v3z a + v3z b\nv3sub :: (Num a) => Vector3 a -> Vector3 a -> Vector3 a\nv3sub a b = Vector3 x y z\n  where x = v3x a - v3x b\n        y = v3y a - v3y b\n        z = v3z a - v3z b\nv3sum :: (Num a) => [Vector3 a] -> Vector3 a\nv3sum vlist = foldl (\\accum v -> v3add v accum) (Vector3 0 0 0) vlist\n\nv3div :: (Fractional a, Num a) => Vector3 a -> Vector3 a -> Vector3 a\nv3div a b = Vector3 x y z\n  where x = v3x a / v3x b\n        y = v3y a / v3y b\n        z = v3z a / v3z b\n\nvx3add :: (Num a) => Vertex3 a -> Vertex3 a -> Vertex3 a\nvx3add a b = Vertex3 x y z\n  where x = vx3x a + vx3x b\n        y = vx3y a + vx3y b\n        z = vx3z a + vx3z b\n\nn3Invert :: Normal3 GLfloat -> Normal3 GLfloat\nn3Invert n = Normal3 x y z\n  where x = -(n3x n)\n        y = -(n3y n)\n        z = -(n3z n)\n\ncolor3AddAlpha :: Color3 GLfloat -> GLfloat -> Color4 GLfloat\ncolor3AddAlpha (Color3 r g b) a = Color4 r g b a\n\ncolor4MulAlpha :: Color4 GLfloat -> GLfloat -> Color4 GLfloat\ncolor4MulAlpha (Color4 r g b a) x = Color4 r g b (a*x)\n\ncolor4MulValue :: Color4 GLfloat -> GLfloat -> Color4 GLfloat\ncolor4MulValue (Color4 r g b a) x = Color4 (r*x) (g*x) (b*x) a\n\ncolor3MulValue :: Color3 GLfloat -> GLfloat -> Color3 GLfloat\ncolor3MulValue (Color3 r g b) x = Color3 (r*x) (g*x) (b*x) \n\n-- }}}\n\n-- Useful for mapping over a list containing tuples of (vertex, vertexNormal): \nvertexWithNormal :: (Vertex3 GLfloat, Normal3 GLfloat) -> IO ()\nvertexWithNormal (v,n) = do normal n\n                            vertex v \n                            return ()\n\nvertexWithNormalAndColor :: (Vertex3 GLfloat, Normal3 GLfloat) -> Color4 GLfloat -> IO ()\nvertexWithNormalAndColor (v,n) c = do color c\n                                      normal n\n                                      vertex v \n                                      return ()\n\ndrawNormal :: (Fractional a, VertexComponent a) => ( Vertex3 a, Normal3 a ) -> IO ()\ndrawNormal (v,n) = do let from = v\n                      let nx   = (n3x n) * 100.0\n                      let ny   = (n3y n) * 100.0\n                      let nz   = (n3z n) * 100.0\n                      let to   = Vertex3 (nx + vx3x v) (ny + vx3y v) (nz + vx3z v)\n                      color $ (Color4 1.0 1.0 1.0 1.0 :: Color4 GLfloat)\n                      renderPrimitive Lines ( do vertex from\n                                                 vertex to )\n\nnormalsFromVertices :: [[ Vertex3 GLfloat ]] -> [ Normal3 GLfloat ]\n-- {{{\nnormalsFromVertices sigs = normalsFromVertices' sigs 0\n\nnormalsFromVertices' :: [[ Vertex3 GLfloat ]] -> Int -> [ Normal3 GLfloat ]\nnormalsFromVertices' sigs xIdx = case sigs of  \n  (sigPrev:sig:sigNext:[]) -> if nSamples > 0 && xIdx < nSamples then resultNormal : normalsFromVertices' sigs (xIdx+1) else []\n    where nSamples = length sig\n          boundx   = \\a -> max 0 (min a (nSamples-1)) :: Int \n          vertexC  = sig !! xIdx\n          vertexR  = sig !! (boundx (xIdx+1))\n          vertexL  = sig !! (boundx (xIdx-1))\n          vertexT  = if length sigPrev > xIdx then sigPrev !! xIdx else vertexC\n          vertexB  = if length sigNext > xIdx then sigNext !! xIdx else vertexC\n          point    = vertexToVector vertexC\n          pointR   = vertexToVector vertexR\n          pointL   = vertexToVector vertexL\n          pointT   = vertexToVector vertexT\n          pointB   = vertexToVector vertexB\n          vR = v3sub pointR point   --   n4  T  n1\n          vT = v3sub pointT point   --       |\n          vL = v3sub pointL point   --    L--C--R\n          vB = v3sub pointB point   --       |\n          n1 = v3cross vT vR        --   n3  B  n2\n          n2 = v3cross vR vB\n          n3 = v3cross vB vL\n          n4 = v3cross vL vT\n          -- no normalization here as GL.normalize is enabled\n          n  = v3div (v3sum [ n1, n2, n3, n4 ]) (Vector3 4.0 4.0 (4.0 :: GLfloat)) \n          resultNormal = n3Invert $ Normal3 (v3x n) (v3y n) (v3z n)\n  _ -> []\n-- }}}\n\ngetViewpointFromModelView :: GLmatrix GLfloat -> IO ( Vector3 GLfloat )\n-- {{{\ngetViewpointFromModelView mvMatrix = do \n  mvMatrixRows <- getMatrixComponents ColumnMajor mvMatrix\n  -- OpenGL float matrix to GSL double matrix: \n  let mvMatrixGSL = (4 >< 4) $ map (\\e -> realToFrac e :: Double) mvMatrixRows\n  -- Invert GSL matrix: \n  let mvMatrixGSLInv = LA.inv ( mvMatrixGSL :: HM.Matrix Double )\n  -- 4th column vector is position of view point. First 3 columns are \n  -- transformation elements. \n  let viewPointProjection = NC.fromList [ 0.0, 0.0, 0.0, 1.0 ]\n  let viewPointModelView = NC.toList $ NC.vXm viewPointProjection mvMatrixGSLInv\n  let viewPoint = Vector3 (realToFrac $ viewPointModelView !! 0) \n                          (realToFrac $ viewPointModelView !! 1) \n                          (realToFrac $ viewPointModelView !! 2) :: Vector3 GLfloat\n  return viewPoint\n-- }}}\n\nfeaturesToIntensity :: FE.SignalFeatures -> FE.FeatureTarget -> AC.ContextSettings -> (GLfloat,GLfloat)\nfeaturesToIntensity features target cSettings = (lCoeff, bCoeff)\n  where loudness     = realToFrac $ FE.totalEnergy features\n        basslevel    = realToFrac $ FE.bassEnergy features \n        lTarget      = FE.featureTargetFromIndex $ AC.featureSignalEnergyTargetIdx cSettings\n        bTarget      = FE.featureTargetFromIndex $ AC.featureBassEnergyTargetIdx cSettings\n        lCoeff       = if lTarget == target || lTarget == FE.GlobalAndLocalTarget then (\n                          realToFrac $ (AC.featureSignalEnergySurfaceCoeff cSettings) * loudness )\n                       else 0.0\n        bCoeff       = if bTarget == target || bTarget == FE.GlobalAndLocalTarget then (\n                          realToFrac $ (AC.featureBassEnergySurfaceCoeff cSettings) * basslevel )\n                       else 0.0 \n\n", "meta": {"hexsha": "d2f7ba28b0ea1808cdcda15f4caca14039b99d39", "size": 15191, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Drool/Utils/RenderHelpers.hs", "max_stars_repo_name": "fuchsto/drool", "max_stars_repo_head_hexsha": "d9318c641a6a94a8450b5118db7b3213a93209ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2019-04-04T17:12:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-21T20:25:55.000Z", "max_issues_repo_path": "src/Drool/Utils/RenderHelpers.hs", "max_issues_repo_name": "fuchsto/drool", "max_issues_repo_head_hexsha": "d9318c641a6a94a8450b5118db7b3213a93209ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Drool/Utils/RenderHelpers.hs", "max_forks_repo_name": "fuchsto/drool", "max_forks_repo_head_hexsha": "d9318c641a6a94a8450b5118db7b3213a93209ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0726817043, "max_line_length": 127, "alphanum_fraction": 0.5840300178, "num_tokens": 4355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.17927717104487445}}
{"text": "{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE RoleAnnotations #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE TypeOperators #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE Trustworthy #-}\n{-# LANGUAGE Rank2Types #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE CPP #-}\n#if __GLASGOW_HASKELL__ >= 800\n{-# LANGUAGE UndecidableSuperClasses #-}\n#endif\n#if __GLASGOW_HASKELL__ >= 708 && __GLASGOW_HASKELL__ < 710\n{-# LANGUAGE NullaryTypeClasses #-}\n#endif\n-----------------------------------------------------------------------------\n-- |\n-- Module      :  Data.Constraint\n-- Copyright   :  (C) 2011-2015 Edward Kmett,\n-- License     :  BSD-style (see the file LICENSE)\n--\n-- Maintainer  :  Edward Kmett <ekmett@gmail.com>\n-- Stability   :  experimental\n-- Portability :  non-portable\n--\n-- @ConstraintKinds@ made type classes into types of a new kind, @Constraint@.\n--\n-- @\n-- 'Eq' :: * -> 'Constraint'\n-- 'Ord' :: * -> 'Constraint'\n-- 'Monad' :: (* -> *) -> 'Constraint'\n-- @\n--\n-- The need for this extension was first publicized in the paper\n--\n-- <http://research.microsoft.com/pubs/67439/gmap3.pdf Scrap your boilerplate with class: extensible generic functions>\n--\n-- by Ralf L\u00e4mmel and Simon Peyton Jones in 2005, which shoehorned all the\n-- things they needed into a custom 'Sat' typeclass.\n--\n-- With @ConstraintKinds@ we can put into code a lot of tools for manipulating\n-- these new types without such awkward workarounds.\n----------------------------------------------------------------------------\nmodule Data.Constraint\n  (\n  -- * The Kind of Constraints\n    Constraint\n  -- * Dictionary\n  , Dict(Dict)\n  , withDict\n  -- * Entailment\n  , (:-)(Sub)\n  , (\\\\)\n  , weaken1, weaken2, contract\n  , strengthen1, strengthen2\n  , (&&&), (***)\n  , trans, refl\n  , Bottom(no)\n  , top, bottom\n  -- * Dict is fully faithful\n  , mapDict\n  , unmapDict\n  -- * Reflection\n  , Class(..)\n  , (:=>)(..)\n  ) where\nimport Control.Applicative\nimport Control.Category\nimport Control.DeepSeq\nimport Control.Monad\nimport Data.Complex\nimport Data.Ratio\nimport Data.Semigroup\nimport Data.Data\nimport qualified GHC.Exts as Exts (Any)\nimport GHC.Exts (Constraint)\nimport Data.Bits (Bits)\nimport Data.Functor.Identity (Identity)\n#if MIN_VERSION_base(4,8,0)\nimport Numeric.Natural (Natural)\n#endif\n#if !MIN_VERSION_base(4,8,0)\nimport Data.Word (Word)\n#endif\n\n-- | Values of type @'Dict' p@ capture a dictionary for a constraint of type @p@.\n--\n-- e.g.\n--\n-- @\n-- 'Dict' :: 'Dict' ('Eq' 'Int')\n-- @\n--\n-- captures a dictionary that proves we have an:\n--\n-- @\n-- instance 'Eq' 'Int\n-- @\n--\n-- Pattern matching on the 'Dict' constructor will bring this instance into scope.\n--\ndata Dict :: Constraint -> * where\n  Dict :: a => Dict a\n  deriving Typeable\n\n\ninstance (Typeable p, p) => Data (Dict p) where\n  gfoldl _ z Dict = z Dict\n  toConstr _ = dictConstr\n  gunfold _ z c = case constrIndex c of\n    1 -> z Dict\n    _ -> error \"gunfold\"\n  dataTypeOf _ = dictDataType\n\ndictConstr :: Constr\ndictConstr = mkConstr dictDataType \"Dict\" [] Prefix\n\ndictDataType :: DataType\ndictDataType = mkDataType \"Data.Constraint.Dict\" [dictConstr]\n\nderiving instance Eq (Dict a)\nderiving instance Ord (Dict a)\nderiving instance Show (Dict a)\n\ninstance NFData (Dict c) where\n  rnf Dict = ()\n\n-- | From a 'Dict', takes a value in an environment where the instance\n-- witnessed by the 'Dict' is in scope, and evaluates it.\n--\n-- Essentially a deconstruction of a 'Dict' into its continuation-style\n-- form.\n--\nwithDict :: Dict a -> (a => r) -> r\nwithDict d r = case d of\n                 Dict -> r\n\ninfixr 9 :-\n\n-- | This is the type of entailment.\n--\n-- @a ':-' b@ is read as @a@ \\\"entails\\\" @b@.\n--\n-- With this we can actually build a category for 'Constraint' resolution.\n--\n-- e.g.\n--\n-- Because @'Eq' a@ is a superclass of @'Ord' a@, we can show that @'Ord' a@\n-- entails @'Eq' a@.\n--\n-- Because @instance 'Ord' a => 'Ord' [a]@ exists, we can show that @'Ord' a@\n-- entails @'Ord' [a]@ as well.\n--\n-- This relationship is captured in the ':-' entailment type here.\n--\n-- Since @p ':-' p@ and entailment composes, ':-' forms the arrows of a\n-- 'Category' of constraints. However, 'Category' only became sufficiently\n-- general to support this instance in GHC 7.8, so prior to 7.8 this instance\n-- is unavailable.\n--\n-- But due to the coherence of instance resolution in Haskell, this 'Category'\n-- has some very interesting properties. Notably, in the absence of\n-- @IncoherentInstances@, this category is \\\"thin\\\", which is to say that\n-- between any two objects (constraints) there is at most one distinguishable\n-- arrow.\n--\n-- This means that for instance, even though there are two ways to derive\n-- @'Ord' a ':-' 'Eq' [a]@, the answers from these two paths _must_ by\n-- construction be equal. This is a property that Haskell offers that is\n-- pretty much unique in the space of languages with things they call \\\"type\n-- classes\\\".\n--\n-- What are the two ways?\n--\n-- Well, we can go from @'Ord' a ':-' 'Eq' a@ via the\n-- superclass relationship, and then from @'Eq' a ':-' 'Eq' [a]@ via the\n-- instance, or we can go from @'Ord' a ':-' 'Ord' [a]@ via the instance\n-- then from @'Ord' [a] ':-' 'Eq' [a]@ through the superclass relationship\n-- and this diagram by definition must \\\"commute\\\".\n--\n-- Diagrammatically,\n--\n-- >                    Ord a\n-- >                ins /     \\ cls\n-- >                   v       v\n-- >             Ord [a]     Eq a\n-- >                cls \\     / ins\n-- >                     v   v\n-- >                    Eq [a]\n--\n-- This safety net ensures that pretty much anything you can write with this\n-- library is sensible and can't break any assumptions on the behalf of\n-- library authors.\nnewtype a :- b = Sub (a => Dict b)\n  deriving Typeable\n\ntype role (:-) nominal nominal\n\n-- TODO: _proper_ Data for @(p ':-' q)@ requires @(:-)@ to be cartesian _closed_.\n--\n-- This is admissable, but not present by default\n\n-- constraint should be instance (Typeable p, Typeable q, p |- q) => Data (p :- q)\ninstance (Typeable p, Typeable q, p, q) => Data (p :- q) where\n  gfoldl _ z (Sub Dict) = z (Sub Dict)\n  toConstr _ = subConstr\n  gunfold _ z c = case constrIndex c of\n    1 -> z (Sub Dict)\n    _ -> error \"gunfold\"\n  dataTypeOf _ = subDataType\n\nsubConstr :: Constr\nsubConstr = mkConstr dictDataType \"Sub\" [] Prefix\n\nsubDataType :: DataType\nsubDataType = mkDataType \"Data.Constraint.:-\" [subConstr]\n\n-- | Possible since GHC 7.8, when 'Category' was made polykinded.\ninstance Category (:-) where\n  id  = refl\n  (.) = trans\n\n-- | Assumes 'IncoherentInstances' doesn't exist.\ninstance Eq (a :- b) where\n  _ == _ = True\n\n-- | Assumes 'IncoherentInstances' doesn't exist.\ninstance Ord (a :- b) where\n  compare _ _ = EQ\n\ninstance Show (a :- b) where\n  showsPrec d _ = showParen (d > 10) $ showString \"Sub Dict\"\n\ninstance a => NFData (a :- b) where\n  rnf (Sub Dict) = ()\n\ninfixl 1 \\\\ -- required comment\n\n-- | Given that @a :- b@, derive something that needs a context @b@, using the context @a@\n(\\\\) :: a => (b => r) -> (a :- b) -> r\nr \\\\ Sub Dict = r\n\n--------------------------------------------------------------------------------\n-- Constraints form a Category\n--------------------------------------------------------------------------------\n\n-- | Transitivity of entailment\n--\n-- If we view @(':-')@ as a Constraint-indexed category, then this is @('.')@\ntrans :: (b :- c) -> (a :- b) -> a :- c\ntrans f g = Sub $ Dict \\\\ f \\\\ g\n\n-- | Reflexivity of entailment\n--\n-- If we view @(':-')@ as a Constraint-indexed category, then this is 'id'\nrefl :: a :- a\nrefl = Sub Dict\n\n--------------------------------------------------------------------------------\n-- (,) is a Bifunctor\n--------------------------------------------------------------------------------\n\n-- | due to the hack for the kind of @(,)@ in the current version of GHC we can't actually\n-- make instances for @(,) :: Constraint -> Constraint -> Constraint@, but @(,)@ is a\n-- bifunctor on the category of constraints. This lets us map over both sides.\n(***) :: (a :- b) -> (c :- d) -> (a, c) :- (b, d)\nf *** g = Sub $ Dict \\\\ f \\\\ g\n\n--------------------------------------------------------------------------------\n-- Constraints are Cartesian\n--------------------------------------------------------------------------------\n\n-- | Weakening a constraint product\n--\n-- The category of constraints is Cartesian. We can forget information.\nweaken1 :: (a, b) :- a\nweaken1 = Sub Dict\n\n-- | Weakening a constraint product\n--\n-- The category of constraints is Cartesian. We can forget information.\nweaken2 :: (a, b) :- b\nweaken2 = Sub Dict\n\nstrengthen1 :: Dict b -> a :- c -> a :- (b,c)\nstrengthen1 d e = unmapDict (const d) &&& e\n\nstrengthen2 :: Dict b -> a :- c -> a :- (c,b)\nstrengthen2 d e = e &&& unmapDict (const d)\n\n-- | Contracting a constraint / diagonal morphism\n--\n-- The category of constraints is Cartesian. We can reuse information.\ncontract :: a :- (a, a)\ncontract = Sub Dict\n\n-- | Constraint product\n--\n-- > trans weaken1 (f &&& g) = f\n-- > trans weaken2 (f &&& g) = g\n(&&&) :: (a :- b) -> (a :- c) -> a :- (b, c)\nf &&& g = Sub $ Dict \\\\ f \\\\ g\n\n--------------------------------------------------------------------------------\n-- Initial and terminal morphisms\n--------------------------------------------------------------------------------\n\n-- | Every constraint implies truth\n--\n-- These are the terminal arrows of the category, and @()@ is the terminal object.\n--\n-- Given any constraint there is a unique entailment of the @()@ constraint from that constraint.\ntop :: a :- ()\ntop = Sub Dict\n\n-- | 'Any' inhabits every kind, including 'Constraint' but is uninhabited, making it impossible to define an instance.\nclass Exts.Any => Bottom where\n  no :: a\n\n-- |\n-- This demonstrates the law of classical logic <http://en.wikipedia.org/wiki/Principle_of_explosion \"ex falso quodlibet\">\nbottom :: Bottom :- a\nbottom = Sub no\n\n--------------------------------------------------------------------------------\n-- Dict is fully faithful\n--------------------------------------------------------------------------------\n\n-- | Apply an entailment to a dictionary.\n--\n-- From a category theoretic perspective 'Dict' is a functor that maps from the category\n-- of constraints (with arrows in ':-') to the category Hask of Haskell data types.\nmapDict :: (a :- b) -> Dict a -> Dict b\nmapDict p Dict = case p of Sub q -> q\n\n-- |\n-- This functor is fully faithful, which is to say that given any function you can write\n-- @Dict a -> Dict b@ there also exists an entailment @a :- b@ in the category of constraints\n-- that you can build.\nunmapDict :: (Dict a -> Dict b) -> a :- b\nunmapDict f = Sub (f Dict)\n\ntype role Dict nominal\n\n--------------------------------------------------------------------------------\n-- Reflection\n--------------------------------------------------------------------------------\n\n-- | Reify the relationship between a class and its superclass constraints as a class\n--\n-- Given a definition such as\n--\n-- @\n-- class Foo a => Bar a\n-- @\n--\n-- you can capture the relationship between 'Bar a' and its superclass 'Foo a' with\n--\n-- @\n-- instance 'Class' (Foo a) (Bar a) where 'cls' = 'Sub' 'Dict'\n-- @\n--\n-- Now the user can use 'cls :: Bar a :- Foo a'\nclass Class b h | h -> b where\n  cls :: h :- b\n\ninfixr 9 :=>\n-- | Reify the relationship between an instance head and its body as a class\n--\n-- Given a definition such as\n--\n-- @\n-- instance Foo a => Foo [a]\n-- @\n--\n-- you can capture the relationship between the instance head and its body with\n--\n-- @\n-- instance Foo a ':=>' Foo [a] where 'ins' = 'Sub' 'Dict'\n-- @\nclass b :=> h | h -> b where\n  ins :: b :- h\n\n-- Bootstrapping\n\ninstance Class () (Class b a) where cls = Sub Dict\ninstance Class () (b :=> a) where cls = Sub Dict\n\ninstance Class b a => () :=> Class b a where ins = Sub Dict\ninstance (b :=> a) => () :=> (b :=> a) where ins = Sub Dict\n\ninstance Class () () where cls = Sub Dict\ninstance () :=> () where ins = Sub Dict\n\n-- Local, Prelude, Applicative, C.M.I and Data.Monoid instances\n\n-- Eq\ninstance Class () (Eq a) where cls = Sub Dict\ninstance () :=> Eq () where ins = Sub Dict\ninstance () :=> Eq Int where ins = Sub Dict\ninstance () :=> Eq Bool where ins = Sub Dict\ninstance () :=> Eq Integer where ins = Sub Dict\ninstance () :=> Eq Float where ins = Sub Dict\ninstance () :=> Eq Double where ins = Sub Dict\ninstance Eq a :=> Eq [a] where ins = Sub Dict\ninstance Eq a :=> Eq (Maybe a) where ins = Sub Dict\ninstance Eq a :=> Eq (Complex a) where ins = Sub Dict\ninstance Eq a :=> Eq (Ratio a) where ins = Sub Dict\ninstance (Eq a, Eq b) :=> Eq (a, b) where ins = Sub Dict\ninstance (Eq a, Eq b) :=> Eq (Either a b) where ins = Sub Dict\ninstance () :=> Eq (Dict a) where ins = Sub Dict\ninstance () :=> Eq (a :- b) where ins = Sub Dict\ninstance () :=> Eq Word where ins = Sub Dict\ninstance Eq a :=> Eq (Identity a) where ins = Sub Dict\n#if MIN_VERSION_base(4,8,0)\ninstance Eq a :=> Eq (Const a b) where ins = Sub Dict\ninstance () :=> Eq Natural where ins = Sub Dict\n#endif\n\n-- Ord\ninstance Class (Eq a) (Ord a) where cls = Sub Dict\ninstance () :=> Ord () where ins = Sub Dict\ninstance () :=> Ord Bool where ins = Sub Dict\ninstance () :=> Ord Int where ins = Sub Dict\ninstance ():=> Ord Integer where ins = Sub Dict\ninstance () :=> Ord Float where ins = Sub Dict\ninstance ():=> Ord Double where ins = Sub Dict\ninstance () :=> Ord Char where ins = Sub Dict\ninstance Ord a :=> Ord (Maybe a) where ins = Sub Dict\ninstance Ord a :=> Ord [a] where ins = Sub Dict\ninstance (Ord a, Ord b) :=> Ord (a, b) where ins = Sub Dict\ninstance (Ord a, Ord b) :=> Ord (Either a b) where ins = Sub Dict\ninstance Integral a :=> Ord (Ratio a) where ins = Sub Dict\ninstance () :=> Ord (Dict a) where ins = Sub Dict\ninstance () :=> Ord (a :- b) where ins = Sub Dict\ninstance () :=> Ord Word where ins = Sub Dict\ninstance Ord a :=> Ord (Identity a) where ins = Sub Dict\n#if MIN_VERSION_base(4,8,0)\ninstance Ord a :=> Ord (Const a b) where ins = Sub Dict\ninstance () :=> Ord Natural where ins = Sub Dict\n#endif\n\n-- Show\ninstance Class () (Show a) where cls = Sub Dict\ninstance () :=> Show () where ins = Sub Dict\ninstance () :=> Show Bool where ins = Sub Dict\ninstance () :=> Show Ordering where ins = Sub Dict\ninstance () :=> Show Char where ins = Sub Dict\ninstance () :=> Show Int where ins = Sub Dict\ninstance Show a :=> Show (Complex a) where ins = Sub Dict\ninstance Show a :=> Show [a] where ins = Sub Dict\ninstance Show a :=> Show (Maybe a) where ins = Sub Dict\ninstance (Show a, Show b) :=> Show (a, b) where ins = Sub Dict\ninstance (Show a, Show b) :=> Show (Either a b) where ins = Sub Dict\ninstance (Integral a, Show a) :=> Show (Ratio a) where ins = Sub Dict\ninstance () :=> Show (Dict a) where ins = Sub Dict\ninstance () :=> Show (a :- b) where ins = Sub Dict\ninstance () :=> Show Word where ins = Sub Dict\ninstance Show a :=> Show (Identity a) where ins = Sub Dict\n#if MIN_VERSION_base(4,8,0)\ninstance Show a :=> Show (Const a b) where ins = Sub Dict\ninstance () :=> Show Natural where ins = Sub Dict\n#endif\n\n-- Read\ninstance Class () (Read a) where cls = Sub Dict\ninstance () :=> Read () where ins = Sub Dict\ninstance () :=> Read Bool where ins = Sub Dict\ninstance () :=> Read Ordering where ins = Sub Dict\ninstance () :=> Read Char where ins = Sub Dict\ninstance () :=> Read Int where ins = Sub Dict\ninstance Read a :=> Read (Complex a) where ins = Sub Dict\ninstance Read a :=> Read [a] where ins = Sub Dict\ninstance Read a :=> Read (Maybe a) where ins = Sub Dict\ninstance (Read a, Read b) :=> Read (a, b) where ins = Sub Dict\ninstance (Read a, Read b) :=> Read (Either a b) where ins = Sub Dict\ninstance (Integral a, Read a) :=> Read (Ratio a) where ins = Sub Dict\ninstance () :=> Read Word where ins = Sub Dict\ninstance Read a :=> Read (Identity a) where ins = Sub Dict\n#if MIN_VERSION_base(4,8,0)\ninstance Read a :=> Read (Const a b) where ins = Sub Dict\ninstance () :=> Read Natural where ins = Sub Dict\n#endif\n\n-- Enum\ninstance Class () (Enum a) where cls = Sub Dict\ninstance () :=> Enum () where ins = Sub Dict\ninstance () :=> Enum Bool where ins = Sub Dict\ninstance () :=> Enum Ordering where ins = Sub Dict\ninstance () :=> Enum Char where ins = Sub Dict\ninstance () :=> Enum Int where ins = Sub Dict\ninstance () :=> Enum Integer where ins = Sub Dict\ninstance () :=> Enum Float where ins = Sub Dict\ninstance () :=> Enum Double where ins = Sub Dict\ninstance Integral a :=> Enum (Ratio a) where ins = Sub Dict\ninstance () :=> Enum Word where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Enum a :=> Enum (Identity a) where ins = Sub Dict\ninstance Enum a :=> Enum (Const a b) where ins = Sub Dict\n#endif\n#if MIN_VERSION_base(4,8,0)\ninstance () :=> Enum Natural where ins = Sub Dict\n#endif\n\n-- Bounded\ninstance Class () (Bounded a) where cls = Sub Dict\ninstance () :=> Bounded () where ins = Sub Dict\ninstance () :=> Bounded Ordering where ins = Sub Dict\ninstance () :=> Bounded Bool where ins = Sub Dict\ninstance () :=> Bounded Int where ins = Sub Dict\ninstance () :=> Bounded Char where ins = Sub Dict\ninstance (Bounded a, Bounded b) :=> Bounded (a,b) where ins = Sub Dict\ninstance () :=> Bounded Word where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Bounded a :=> Bounded (Identity a) where ins = Sub Dict\ninstance Bounded a :=> Bounded (Const a b) where ins = Sub Dict\n#endif\n\n-- Num\ninstance Class () (Num a) where cls = Sub Dict\ninstance () :=> Num Int where ins = Sub Dict\ninstance () :=> Num Integer where ins = Sub Dict\ninstance () :=> Num Float where ins = Sub Dict\ninstance () :=> Num Double where ins = Sub Dict\ninstance RealFloat a :=> Num (Complex a) where ins = Sub Dict\ninstance Integral a :=> Num (Ratio a) where ins = Sub Dict\ninstance () :=> Num Word where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Num a :=> Num (Identity a) where ins = Sub Dict\ninstance Num a :=> Num (Const a b) where ins = Sub Dict\n#endif\n#if MIN_VERSION_base(4,8,0)\ninstance () :=> Num Natural where ins = Sub Dict\n#endif\n\n-- Real\ninstance Class (Num a, Ord a) (Real a) where cls = Sub Dict\ninstance () :=> Real Int where ins = Sub Dict\ninstance () :=> Real Integer where ins = Sub Dict\ninstance () :=> Real Float where ins = Sub Dict\ninstance () :=> Real Double where ins = Sub Dict\ninstance Integral a :=> Real (Ratio a) where ins = Sub Dict\ninstance () :=> Real Word where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Real a :=> Real (Identity a) where ins = Sub Dict\ninstance Real a :=> Real (Const a b) where ins = Sub Dict\n#endif\n#if MIN_VERSION_base(4,8,0)\ninstance () :=> Real Natural where ins = Sub Dict\n#endif\n\n-- Integral\ninstance Class (Real a, Enum a) (Integral a) where cls = Sub Dict\ninstance () :=> Integral Int where ins = Sub Dict\ninstance () :=> Integral Integer where ins = Sub Dict\ninstance () :=> Integral Word where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Integral a :=> Integral (Identity a) where ins = Sub Dict\ninstance Integral a :=> Integral (Const a b) where ins = Sub Dict\n#endif\n#if MIN_VERSION_base(4,8,0)\ninstance () :=> Integral Natural where ins = Sub Dict\n#endif\n\n-- Bits\ninstance Class (Eq a) (Bits a) where cls = Sub Dict\ninstance () :=> Bits Bool where ins = Sub Dict\ninstance () :=> Bits Int where ins = Sub Dict\ninstance () :=> Bits Integer where ins = Sub Dict\ninstance () :=> Bits Word where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Bits a :=> Bits (Identity a) where ins = Sub Dict\ninstance Bits a :=> Bits (Const a b) where ins = Sub Dict\n#endif\n#if MIN_VERSION_base(4,8,0)\ninstance () :=> Bits Natural where ins = Sub Dict\n#endif\n\n-- Fractional\ninstance Class (Num a) (Fractional a) where cls = Sub Dict\ninstance () :=> Fractional Float where ins = Sub Dict\ninstance () :=> Fractional Double where ins = Sub Dict\ninstance RealFloat a :=> Fractional (Complex a) where ins = Sub Dict\ninstance Integral a :=> Fractional (Ratio a) where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Fractional a :=> Fractional (Identity a) where ins = Sub Dict\ninstance Fractional a :=> Fractional (Const a b) where ins = Sub Dict\n#endif\n\n-- Floating\ninstance Class (Fractional a) (Floating a) where cls = Sub Dict\ninstance () :=> Floating Float where ins = Sub Dict\ninstance () :=> Floating Double where ins = Sub Dict\ninstance RealFloat a :=> Floating (Complex a) where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Floating a :=> Floating (Identity a) where ins = Sub Dict\ninstance Floating a :=> Floating (Const a b) where ins = Sub Dict\n#endif\n\n-- RealFrac\ninstance Class (Real a, Fractional a) (RealFrac a) where cls = Sub Dict\ninstance () :=> RealFrac Float where ins = Sub Dict\ninstance () :=> RealFrac Double where ins = Sub Dict\ninstance Integral a :=> RealFrac (Ratio a) where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance RealFrac a :=> RealFrac (Identity a) where ins = Sub Dict\ninstance RealFrac a :=> RealFrac (Const a b) where ins = Sub Dict\n#endif\n\n-- RealFloat\ninstance Class (RealFrac a, Floating a) (RealFloat a) where cls = Sub Dict\ninstance () :=> RealFloat Float where ins = Sub Dict\ninstance () :=> RealFloat Double where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance RealFloat a :=> RealFloat (Identity a) where ins = Sub Dict\ninstance RealFloat a :=> RealFloat (Const a b) where ins = Sub Dict\n#endif\n\n-- Semigroup\ninstance Class () (Semigroup a) where cls = Sub Dict\ninstance () :=> Semigroup () where ins = Sub Dict\ninstance () :=> Semigroup Ordering where ins = Sub Dict\ninstance () :=> Semigroup [a] where ins = Sub Dict\ninstance Semigroup a :=> Semigroup (Maybe a) where ins = Sub Dict\ninstance (Semigroup a, Semigroup b) :=> Semigroup (a, b) where ins = Sub Dict\ninstance Semigroup a :=> Semigroup (Const a b) where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Semigroup a :=> Semigroup (Identity a) where ins = Sub Dict\n#endif\n#if MIN_VERSION_base(4,10,0)\ninstance Semigroup a :=> Semigroup (IO a) where ins = Sub Dict\n#endif\n\n-- Monoid\n#if MIN_VERSION_base(4,11,0)\ninstance Class (Semigroup a) (Monoid a) where cls = Sub Dict\n#else\ninstance Class () (Monoid a) where cls = Sub Dict\n#endif\ninstance () :=> Monoid () where ins = Sub Dict\ninstance () :=> Monoid Ordering where ins = Sub Dict\ninstance () :=> Monoid [a] where ins = Sub Dict\ninstance Monoid a :=> Monoid (Maybe a) where ins = Sub Dict\ninstance (Monoid a, Monoid b) :=> Monoid (a, b) where ins = Sub Dict\ninstance Monoid a :=> Monoid (Const a b) where ins = Sub Dict\n#if MIN_VERSION_base(4,9,0)\ninstance Monoid a :=> Monoid (Identity a) where ins = Sub Dict\ninstance Monoid a :=> Monoid (IO a) where ins = Sub Dict\n#endif\n\n-- Functor\ninstance Class () (Functor f) where cls = Sub Dict\ninstance () :=> Functor [] where ins = Sub Dict\ninstance () :=> Functor Maybe where ins = Sub Dict\ninstance () :=> Functor (Either a) where ins = Sub Dict\ninstance () :=> Functor ((->) a) where ins = Sub Dict\ninstance () :=> Functor ((,) a) where ins = Sub Dict\ninstance () :=> Functor IO where ins = Sub Dict\ninstance Monad m :=> Functor (WrappedMonad m) where ins = Sub Dict\ninstance () :=> Functor Identity where ins = Sub Dict\ninstance () :=> Functor (Const a) where ins = Sub Dict\n\n-- Applicative\ninstance Class (Functor f) (Applicative f) where cls = Sub Dict\ninstance () :=> Applicative [] where ins = Sub Dict\ninstance () :=> Applicative Maybe where ins = Sub Dict\ninstance () :=> Applicative (Either a) where ins = Sub Dict\ninstance () :=> Applicative ((->)a) where ins = Sub Dict\ninstance () :=> Applicative IO where ins = Sub Dict\ninstance Monoid a :=> Applicative ((,)a) where ins = Sub Dict\ninstance Monoid a :=> Applicative (Const a) where ins = Sub Dict\ninstance Monad m :=> Applicative (WrappedMonad m) where ins = Sub Dict\n\n-- Alternative\ninstance Class (Applicative f) (Alternative f) where cls = Sub Dict\ninstance () :=> Alternative [] where ins = Sub Dict\ninstance () :=> Alternative Maybe where ins = Sub Dict\ninstance MonadPlus m :=> Alternative (WrappedMonad m) where ins = Sub Dict\n\n-- Monad\n#if MIN_VERSION_base(4,8,0)\ninstance Class (Applicative f) (Monad f) where cls = Sub Dict\n#else\ninstance Class () (Monad f) where cls = Sub Dict\n#endif\ninstance () :=> Monad [] where ins = Sub Dict\ninstance () :=> Monad ((->) a) where ins = Sub Dict\ninstance () :=> Monad (Either a) where ins = Sub Dict\ninstance () :=> Monad IO where ins = Sub Dict\ninstance () :=> Monad Identity where ins = Sub Dict\n\n-- MonadPlus\n#if MIN_VERSION_base(4,8,0)\ninstance Class (Monad f, Alternative f) (MonadPlus f) where cls = Sub Dict\n#else\ninstance Class (Monad f) (MonadPlus f) where cls = Sub Dict\n#endif\ninstance () :=> MonadPlus [] where ins = Sub Dict\ninstance () :=> MonadPlus Maybe where ins = Sub Dict\n\n--------------------------------------------------------------------------------\n-- UndecidableInstances\n--------------------------------------------------------------------------------\n\ninstance a :=> Enum (Dict a) where ins = Sub Dict\ninstance a => Enum (Dict a) where\n  toEnum _ = Dict\n  fromEnum Dict = 0\n\ninstance a :=> Bounded (Dict a) where ins = Sub Dict\ninstance a => Bounded (Dict a) where\n  minBound = Dict\n  maxBound = Dict\n\ninstance a :=> Read (Dict a) where ins = Sub Dict\nderiving instance a => Read (Dict a)\n\ninstance () :=> Semigroup (Dict a) where ins = Sub Dict\ninstance Semigroup (Dict a) where\n  Dict <> Dict = Dict\n\ninstance a :=> Monoid (Dict a) where ins = Sub Dict\ninstance a => Monoid (Dict a) where\n#if !(MIN_VERSION_base(4,11,0))\n  mappend = (<>)\n#endif\n  mempty = Dict\n", "meta": {"hexsha": "ecd0d4744abed40c1894560fbded6652fdbc8752", "size": 25734, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Data/Constraint.hs", "max_stars_repo_name": "phadej/constraints", "max_stars_repo_head_hexsha": "017774ed1fcd8e8df67d28b5de36cd50f4a528da", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Data/Constraint.hs", "max_issues_repo_name": "phadej/constraints", "max_issues_repo_head_hexsha": "017774ed1fcd8e8df67d28b5de36cd50f4a528da", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Data/Constraint.hs", "max_forks_repo_name": "phadej/constraints", "max_forks_repo_head_hexsha": "017774ed1fcd8e8df67d28b5de36cd50f4a528da", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9172320217, "max_line_length": 122, "alphanum_fraction": 0.6295950882, "num_tokens": 6956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.17885225045000092}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE UndecidableInstances #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE NamedFieldPuns #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ViewPatterns #-}\n\nmodule Language.Grappa.Interp.StandardHORepr where\n\nimport Data.Vector (Vector)\nimport qualified Data.Vector as V\nimport Control.Monad\n\nimport Numeric.LinearAlgebra hiding (R, Uniform, (<>), Vector)\n\nimport Language.Grappa.Distribution\nimport Language.Grappa.Interp\nimport Language.Grappa.GrappaInternals\nimport Language.Grappa.Frontend.DataSource\n\nimport qualified Numeric.Log as Log\n\nimport qualified Numeric.AD.Mode.Reverse as ADR\nimport qualified Numeric.AD.Internal.Reverse as ADR\nimport qualified Data.Reflection as ADR (Reifies)\n\n\n----------------------------------------------------------------------\n-- * The StandardHORepr Representation\n----------------------------------------------------------------------\n\n-- | The type tag for the standard higher-order representation, which is\n-- parameterized by a monad and by the representation types for reals and ints\ndata StandardHORepr (m :: * -> *) (r :: *) (i :: *) :: *\n\n-- | The type family for 'StandardHORepr' expressions\ntype family StandardHOReprF m r i a :: * where\n  StandardHOReprF m r i (a -> b) =\n    (StandardHOReprF m r i a -> StandardHOReprF m r i b)\n  StandardHOReprF m r i (Dist a) =\n    (DistVar (StandardHORepr m r i) a -> m (StandardHOReprF m r i a))\n  StandardHOReprF m r i (ADT adt) =\n    adt (GExpr (StandardHORepr m r i)) (ADT adt)\n  StandardHOReprF m r i (Vector a) = Vector (StandardHOReprF m r i a)\n  StandardHOReprF m r i Bool    = Bool\n  StandardHOReprF m r i Int     = i\n  StandardHOReprF m r i Prob    = Log.Log r\n  StandardHOReprF m r i R       = r\n  StandardHOReprF m r i RMatrix = Matrix r\n  StandardHOReprF m r i a       = a\n\ninstance ValidExprRepr (StandardHORepr m r i) where\n  type GExprRepr (StandardHORepr m r i) a = StandardHOReprF m r i a\n  interp__'bottom = error \"StandardHORepr: unexpected bottom!\"\n  interp__'injTuple !tup = GExpr tup\n  interp__'projTuple (GExpr !tup) k = k tup\n  interp__'app (GExpr !f) (GExpr x) = GExpr (f x)\n  interp__'lam f = GExpr (unGExpr . f . GExpr)\n  interp__'fix f = f (interp__'fix f)\n\ninstance StrongTupleRepr (StandardHORepr m r i) where\n  interp__'strongProjTuple (GExpr tup) = tup\n\n-- | Helper to match on v-expressions of atomic type in the 'StandardHORepr': if\n-- the 'DistVar' is not a 'VParam', then destructure it and pass it to the\n-- continuation (the 2nd argument); otherwise, return the failure continuation\n-- (the 3rd argument)\nmatchHOReprAtomicDistVar ::\n  (IsAtomic a ~ 'True, EmbedRepr (StandardHORepr m r i) a) =>\n  DistVar (StandardHORepr m r i) a ->\n  (GExpr (StandardHORepr m r i) a -> ret) -> ret -> ret\nmatchHOReprAtomicDistVar VParam _ ret = ret\nmatchHOReprAtomicDistVar (VData (GData a)) k _ = k $ embedRepr a\nmatchHOReprAtomicDistVar (VData GNoData) _ ret = ret\nmatchHOReprAtomicDistVar (VExpr e) k _ = k e\n\n-- | Test if a v-expression of atomic type is a \"missing value\"\nisMissingHOReprAtomicDistVar ::\n  (IsAtomic a ~ 'True, EmbedRepr (StandardHORepr m r i) a) =>\n  DistVar (StandardHORepr m r i) a -> Bool\nisMissingHOReprAtomicDistVar dv =\n  matchHOReprAtomicDistVar dv (\\_ -> False) True\n\n-- | Helper to match on v-expressions in the 'StandardHORepr': if the 'DistVar'\n-- is not a 'VParam', then destructure it and pass it to the continuation (the\n-- 2nd argument); otherwise, return the failure continuation (the 3rd argument)\nmatchHOReprADTDistVar ::\n  TraversableADT adt =>\n  DistVar (StandardHORepr m r i) (ADT adt) ->\n  (adt (DistVar (StandardHORepr m r i)) (ADT adt) -> ret) -> ret -> ret\nmatchHOReprADTDistVar VParam _ ret = ret\nmatchHOReprADTDistVar (VData (GData (ADT adt))) k _ =\n  k $ mapADT (VData . GData . unId) adt\nmatchHOReprADTDistVar (VData GNoData) _ ret = ret\nmatchHOReprADTDistVar (VData (GADTData adt)) k _ = k $ mapADT VData adt\nmatchHOReprADTDistVar (VExpr (GExpr adt)) k _ = k $ mapADT VExpr adt\nmatchHOReprADTDistVar (VADT adt) k _ = k adt\n\n-- | Recursively match a v-expression with list type, returning a list of\n-- 'DistVar's in the list along with a 'Bool' flag indicating whether the list\n-- ends with a \"missing list\", i.e., a 'VParam' or @'VData' 'GNoData'@\nmatchHOReprListDistVar :: DistVar (StandardHORepr m r i) (GList a) ->\n                          ([DistVar (StandardHORepr m r i) a], Bool)\nmatchHOReprListDistVar dv =\n  matchHOReprADTDistVar dv\n  (\\adt -> case adt of\n      Nil -> ([], False)\n      Cons hdv tlv ->\n        let (l, flag) = matchHOReprListDistVar tlv in\n        (hdv:l, flag))\n  ([], True)\n\nmatchHOReprVectorDistVar ::\n  DistVar (StandardHORepr m r i) (Vector a) ->\n  (Vector (DistVar (StandardHORepr m r i) a) -> ret) -> ret -> ret\nmatchHOReprVectorDistVar VParam _ ret = ret\nmatchHOReprVectorDistVar (VData (GData a)) k _ = k $ V.map (VData . GData) a\nmatchHOReprVectorDistVar (VData GNoData) _ ret = ret\nmatchHOReprVectorDistVar (VExpr (GExpr dvs)) k _ = k $ V.map (VExpr . GExpr) dvs\n\ninstance Monad m => ValidRepr (StandardHORepr m r i) where\n  type GVExprRepr (StandardHORepr m r i) a =\n    DistVar (StandardHORepr m r i) a\n  type GStmtRepr (StandardHORepr m r i) a = m (StandardHOReprF m r i a)\n\n  interp__'projTupleStmt (GExpr !tup) k = k tup\n\n  interp__'vInjTuple !tup = GVExpr (VADT $ mapADT unGVExpr tup)\n  interp__'vProjTuple (GVExpr ve) k =\n    matchHOReprADTDistVar ve (k . mapADT GVExpr)\n    (k $ buildTuple $ GVExpr VParam)\n\n  interp__'vwild k = k (GVExpr VParam)\n  interp__'vlift e k = k (GVExpr $ VExpr e)\n\n  interp__'return (GExpr !x) = GStmt (return x)\n  interp__'let rhs body = body rhs\n  interp__'sample (GExpr !d) (GVExpr !dv) k = GStmt $ do\n    !x <- d dv\n    unGStmt $ k (GExpr x)\n\n  interp__'mkDist f = GExpr (\\ dv -> unGStmt $ f $ GVExpr dv)\n\ninstance TraversableADT adt =>\n         Interp__ADT__Expr (StandardHORepr m r i) adt where\n  interp__'injADT adt = GExpr adt\n  interp__'projADT (GExpr adt) k = k adt\n  interp__'projMatchADT (GExpr adt) _ matcher k_succ k_fail =\n    if applyCtorMatcher matcher adt then k_succ adt else k_fail\n\ninstance (Monad m, TraversableADT adt) =>\n         Interp__ADT (StandardHORepr m r i) adt where\n  interp__'vInjADT adt =\n    GVExpr (VADT $ mapADT unGVExpr adt)\n  interp__'vProjMatchADT (GVExpr ve) ctor matcher k_succ k_fail =\n    matchHOReprADTDistVar ve\n    (\\adt ->\n      if applyCtorMatcher matcher adt then\n        k_succ (mapADT GVExpr adt)\n      else k_fail)\n    (k_succ $ mapADT (const $ GVExpr VParam) ctor)\n\ninstance Interp__'source (StandardHORepr m Double Int) a where\n  interp__'source src =\n    GVExpr . VData <$> interpSource src\n\ninstance EmbedRepr (StandardHORepr m Double i) R where\n  embedRepr = GExpr\n\ninstance EmbedRepr (StandardHORepr m Double i) Prob where\n  embedRepr = GExpr . fromProb\n\ninstance ADR.Reifies s ADR.Tape =>\n         EmbedRepr (StandardHORepr m (ADR.Reverse s Double) i) R where\n  embedRepr = GExpr . ADR.auto\n\ninstance ADR.Reifies s ADR.Tape =>\n         EmbedRepr (StandardHORepr m (ADR.Reverse s Double) i) Prob where\n  embedRepr = GExpr . fmap ADR.auto . fromProb\n\ninstance Num i => EmbedRepr (StandardHORepr m r i) Int where\n  embedRepr = GExpr . fromIntegral\n\ninstance EmbedRepr (StandardHORepr m r i) Bool where\n  embedRepr = GExpr\n\ninstance MapC (EmbedRepr (StandardHORepr m r i)) ts =>\n         EmbedRepr (StandardHORepr m r i) (ADT (TupleF ts)) where\n  embedRepr = GExpr . helper . unADT where\n    helper :: MapC (EmbedRepr (StandardHORepr m r i)) ts' =>\n              TupleF ts' Id any -> TupleF ts' (GExpr (StandardHORepr m r i)) any\n    helper (Tuple0) = Tuple0\n    helper (Tuple1 (Id a)) = Tuple1 (embedRepr a)\n    helper (Tuple2 (Id a) (Id b)) =\n      Tuple2 (embedRepr a) (embedRepr b)\n    helper (Tuple3 (Id a) (Id b) (Id c)) =\n      Tuple3 (embedRepr a) (embedRepr b) (embedRepr c)\n    helper (Tuple4 (Id a) (Id b) (Id c) (Id d)) =\n      Tuple4 (embedRepr a) (embedRepr b) (embedRepr c) (embedRepr d)\n    helper (TupleN (Id a) (Id b) (Id c) (Id d) (Id e) tup) =\n      TupleN (embedRepr a) (embedRepr b) (embedRepr c) (embedRepr d)\n      (embedRepr e) (helper tup)\n\ninstance EmbedRepr (StandardHORepr m Double i) a =>\n         EmbedRepr (StandardHORepr m Double i) (Vector a) where\n  embedRepr xs = GExpr $ V.map (unGExpr . helper) xs where\n    helper :: EmbedRepr (StandardHORepr m Double i) a => a ->\n              GExpr (StandardHORepr m Double i) a\n    helper = embedRepr\n\n\n----------------------------------------------------------------------\n-- Boolean and comparison operations\n----------------------------------------------------------------------\n\ninstance Interp__'ifThenElse (StandardHORepr m r i) where\n  interp__'ifThenElse (GExpr c) t e = if c then t else e\n\ninstance Monad m => Interp__'vmatchSwitch (StandardHORepr m r Int) where\n  interp__'vmatchSwitch (GExpr i) stmts = stmts !! i\n\ninstance Interp__not (StandardHORepr m r i) where\n  interp__not = GExpr not\n\ninstance Interp__'amp'amp (StandardHORepr m r i) where\n  interp__'amp'amp = GExpr (&&)\n\ninstance Interp__'bar'bar (StandardHORepr m r i) where\n  interp__'bar'bar = GExpr (||)\n\ninstance (Eq a, Eq (StandardHOReprF m r i a)) =>\n         Interp__'eq'eq (StandardHORepr m r i) a where\n  interp__'eq'eq = GExpr (==)\n\ninstance (Ord a, Ord (StandardHOReprF m r i a)) =>\n         Interp__'lt (StandardHORepr m r i) a where\n  interp__'lt = GExpr (<)\n\ninstance (Ord a, Ord (StandardHOReprF m r i a)) =>\n         Interp__'gt (StandardHORepr m r i) a where\n  interp__'gt = GExpr (>)\n\ninstance (Ord a, Ord (StandardHOReprF m r i a)) =>\n         Interp__'lt'eq (StandardHORepr m r i) a where\n  interp__'lt'eq = GExpr (<=)\n\ninstance (Ord a, Ord (StandardHOReprF m r i a)) =>\n         Interp__'gt'eq (StandardHORepr m r i) a where\n  interp__'gt'eq = GExpr (>=)\n\ninstance (Ord a, Ord (StandardHOReprF m r i a)) =>\n         Interp__min (StandardHORepr m r i) a where\n  interp__min = GExpr min\n\ninstance (Ord a, Ord (StandardHOReprF m r i a)) =>\n         Interp__max (StandardHORepr m r i) a where\n  interp__max = GExpr max\n\n\n----------------------------------------------------------------------\n-- Numeric Operations\n----------------------------------------------------------------------\n\ninstance (Num a, Num (StandardHOReprF m r i a)) =>\n         Interp__'plus (StandardHORepr m r i) a where\n  interp__'plus = GExpr (+)\n\ninstance (Num a, Num (StandardHOReprF m r i a)) =>\n         Interp__'minus (StandardHORepr m r i) a where\n  interp__'minus = GExpr (-)\n\ninstance (Num a, Num (StandardHOReprF m r i a)) =>\n         Interp__'times (StandardHORepr m r i) a where\n  interp__'times = GExpr (*)\n\ninstance (Num a, Num (StandardHOReprF m r i a)) =>\n         Interp__negate (StandardHORepr m r i) a where\n  interp__negate = GExpr negate\n\ninstance (Num a, Num (StandardHOReprF m r i a)) =>\n         Interp__abs (StandardHORepr m r i) a where\n  interp__abs = GExpr abs\n\ninstance (Num a, Num (StandardHOReprF m r i a)) =>\n         Interp__signum (StandardHORepr m r i) a where\n  interp__signum = GExpr signum\n\ninstance (Num a, Num (StandardHOReprF m r i a)) =>\n         Interp__fromInteger (StandardHORepr m r i) a where\n  interp__fromInteger = GExpr fromInteger\n\ninstance (Num a, Num (StandardHOReprF m r i a)) =>\n         Interp__'integer (StandardHORepr m r i) a where\n  interp__'integer n = GExpr (fromInteger n)\n\ninstance (Interp__'integer (StandardHORepr m r i) a,\n          Eq (StandardHOReprF m r i a))\n         => Interp__'eqInteger (StandardHORepr m r i) a where\n  interp__'eqInteger (GExpr x) (GExpr y) = GExpr (x == y)\n\n\ninstance (Fractional a, Fractional (StandardHOReprF m r i a)) =>\n         Interp__'div (StandardHORepr m r i) a where\n  interp__'div = GExpr (/)\n\ninstance (Fractional a, Fractional (StandardHOReprF m r i a)) =>\n         Interp__recip (StandardHORepr m r i) a where\n  interp__recip = GExpr recip\n\ninstance (Fractional a, Fractional (StandardHOReprF m r i a)) =>\n         Interp__fromRational (StandardHORepr m r i) a where\n  interp__fromRational = GExpr fromRational\n\ninstance (Fractional a, Fractional (StandardHOReprF m r i a)) =>\n         Interp__'rational (StandardHORepr m r i) a where\n  interp__'rational n = GExpr (fromRational n)\n\ninstance (Interp__'rational (StandardHORepr m r i) a,\n          Eq (StandardHOReprF m r i a))\n         => Interp__'eqRational (StandardHORepr m r i) a where\n  interp__'eqRational (GExpr x) (GExpr y) = GExpr (x == y)\n\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__pi (StandardHORepr m r i) a where\n  interp__pi = GExpr pi\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__exp (StandardHORepr m r i) a where\n  interp__exp = GExpr exp\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__log (StandardHORepr m r i) a where\n  interp__log = GExpr log\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__sqrt (StandardHORepr m r i) a where\n  interp__sqrt = GExpr sqrt\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__'times'times (StandardHORepr m r i) a where\n  interp__'times'times = GExpr (**)\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__logBase (StandardHORepr m r i) a where\n  interp__logBase = GExpr logBase\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__sin (StandardHORepr m r i) a where\n  interp__sin = GExpr sin\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__cos (StandardHORepr m r i) a where\n  interp__cos = GExpr cos\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__tan (StandardHORepr m r i) a where\n  interp__tan = GExpr tan\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__asin (StandardHORepr m r i) a where\n  interp__asin = GExpr asin\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__acos (StandardHORepr m r i) a where\n  interp__acos = GExpr acos\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__atan (StandardHORepr m r i) a where\n  interp__atan = GExpr atan\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__sinh (StandardHORepr m r i) a where\n  interp__sinh = GExpr sinh\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__cosh (StandardHORepr m r i) a where\n  interp__cosh = GExpr cosh\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__tanh (StandardHORepr m r i) a where\n  interp__tanh = GExpr tanh\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__asinh (StandardHORepr m r i) a where\n  interp__asinh = GExpr asinh\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__acosh (StandardHORepr m r i) a where\n  interp__acosh = GExpr acosh\n\ninstance (Floating a, Floating (StandardHOReprF m r i a)) =>\n         Interp__atanh (StandardHORepr m r i) a where\n  interp__atanh = GExpr atanh\n\n\n----------------------------------------------------------------------\n-- Probability expression operations\n----------------------------------------------------------------------\n\ninstance (Ord r, Floating r) => Interp__realToProb (StandardHORepr m r i) where\n  interp__realToProb = GExpr (Log.Exp . log . toNonNeg) where\n    toNonNeg :: (Ord r, Floating r) => r -> r\n    toNonNeg r = if r < 0 then 0 else r\n\ninstance Interp__logRealToProb (StandardHORepr m r i) where\n  interp__logRealToProb = GExpr Log.Exp\n\ninstance Floating r => Interp__probToReal (StandardHORepr m r i) where\n  interp__probToReal = GExpr (exp . Log.ln)\n\ninstance Interp__probToLogReal (StandardHORepr m r i) where\n  interp__probToLogReal = GExpr Log.ln\n\ninstance HasGamma r => Interp__gammaProb (StandardHORepr m r i) where\n  interp__gammaProb = GExpr (Log.Exp . logGamma)\n\ninstance HasGamma r => Interp__digamma (StandardHORepr m r i) where\n  interp__digamma = GExpr digamma\n\n\n----------------------------------------------------------------------\n-- Misc operations\n----------------------------------------------------------------------\n\ninstance (Show a, Show (StandardHOReprF m r i a), i ~ Int) =>\n         Interp__gtrace (StandardHORepr m r i) a b where\n  interp__gtrace = GExpr gtrace\n\ninstance i ~ Int => Interp__gerror (StandardHORepr m r i) a where\n  interp__gerror = GExpr gerror\n\n\n----------------------------------------------------------------------\n-- * Distributions Supported by All 'StandardHORepr' Representations\n----------------------------------------------------------------------\n\ninstance Monad m => Interp__ctorDist__ListF (StandardHORepr m r i) where\n  interp__ctorDist__Nil = GExpr $ \\ mkNil dv ->\n    do _ <-\n         matchHOReprADTDistVar dv\n         (\\adt -> case adt of\n             Nil -> mkNil (VADT Tuple0)\n             Cons _ _ -> error \"Unexpected Cons\")\n         (mkNil VParam)\n       return Nil\n\n  interp__ctorDist__Cons = GExpr $ \\ mkCons dv ->\n    do (Tuple2 hd tl) <-\n         matchHOReprADTDistVar dv\n         (\\adt -> case adt of\n             Nil -> error \"Unexpected Nil\"\n             Cons hdv tlv -> mkCons (VADT (Tuple2 hdv tlv)))\n         (mkCons (VADT (Tuple2 VParam VParam)))\n       return (Cons hd tl)\n\n\n-- If a repr can do a categorical, it can do an ADT distribution on lists\ninstance (Monad m, Num i, Eq i, Show i,\n          Interp__categorical (StandardHORepr m r i)) =>\n         Interp__adtDist__ListF (StandardHORepr m r i) where\n  interp__adtDist__ListF =\n    GExpr $ \\ probNil mkNil probCons mkCons dvList ->\n    let\n      -- Build a categorical distribution for the constructor, where 0 -> Nil\n      -- and 1 -> Cons\n      ctor_dist :: DistVar (StandardHORepr m r i) Int ->\n                   m (StandardHOReprF m r i Int)\n      ctor_dist =\n        unGExpr (interp__categorical\n                 :: GExpr (StandardHORepr m r i) (GList Prob -> Dist Int)) $\n        fromHaskellListF GExpr [GExpr probNil, GExpr probCons]\n      -- Helper wrapper around mkNil\n      mkNilH = mkNil (VADT Tuple0)\n      -- Helper wrapper around mkCons, that takes vars for the head and tail\n      mkConsH hdv tlv =\n        do Tuple2 hd tl <- mkCons (VADT (Tuple2 hdv tlv))\n           return (Cons hd tl) in\n\n    matchHOReprADTDistVar dvList\n    (\\adt -> case adt of\n        Nil ->\n          void (ctor_dist $ VData $ GData 0) >> void mkNilH >> return Nil\n        Cons hdv tlv ->\n          void (ctor_dist $ VData $ GData 1) >> mkConsH hdv tlv)\n    (do ctor_choice <- ctor_dist VParam\n        case ctor_choice of\n          0 -> void mkNilH >> return Nil\n          1 -> mkConsH VParam VParam\n          _ -> error (\"ListF: Invalid constructor choice: \"\n                      ++ show ctor_choice))\n\n\n--\n-- * Vector Operations\n--\n\ninstance (Monad m, i ~ Int, EmbedRepr (StandardHORepr m r Int) a) =>\n         Interp__vec_iid (StandardHORepr m r i) a where\n  interp__vec_iid = GExpr $ \\len d dv ->\n    matchHOReprVectorDistVar dv\n    (\\dvs ->\n      if V.length dvs == len then V.mapM d dvs else\n        error \"vec_iid: incorrect vector length on input\")\n    (V.replicateM len (d VParam))\n\n{-\n-- | Build a distribution on 'Vector's from one on lists\ninstance (Monad m, EmbedRepr (StandardHORepr m r Int) a) =>\n         Interp__vec_dist (StandardHORepr m r Int) a where\n  interp__vec_dist = GExpr $ \\d dv ->\n    matchHOReprVectorDistVar dv\n    (\\dvs ->\n      V.fromList <$> toHaskellListF unGExpr <$> unGExpr <$>\n      d _)\n    _\n-}\n\ninstance Monad m => Interp__vec_nil_dist (StandardHORepr m r i) a where\n  interp__vec_nil_dist = GExpr $ \\dv ->\n    matchHOReprVectorDistVar dv\n    (\\dvs ->\n      if V.length dvs == 0 then return V.empty else\n        error \"vec_nil_dist: non-empty vector!\")\n    (return V.empty)\n\ninstance Monad m => Interp__vec_cons_dist (StandardHORepr m r i) a where\n  interp__vec_cons_dist = GExpr $ \\d dv ->\n    do (Tuple2 (GExpr hd) (GExpr tl)) <-\n         case dv of\n           VParam -> d VParam\n           VData (GData xs) ->\n             if V.length xs == 0 then\n               error \"vec_cons_dist: empty vector!\"\n             else\n               d $ VData $ GData $ ADT $ Tuple2 (Id $ V.head xs) (Id $ V.tail xs)\n           VData GNoData -> d (VData GNoData)\n           VExpr (GExpr es) ->\n             if V.length es == 0 then\n               error \"vec_cons_dist: empty vector!\"\n             else\n               d $ VExpr $ GExpr $ Tuple2 (GExpr $ V.head es) (GExpr $ V.tail es)\n       return (V.cons hd tl)\n\ninstance Interp__vec_head (StandardHORepr m r i) a where\n  interp__vec_head = GExpr V.head\n\ninstance Interp__vec_tail (StandardHORepr m r i) a where\n  interp__vec_tail = GExpr V.tail\n\ninstance i ~ Int => Interp__vec_length (StandardHORepr m r i) a where\n  interp__vec_length = GExpr V.length\n\n\n--\n-- * Matrix Operations\n--\n\n-- FIXME: matrix operations!\n", "meta": {"hexsha": "bf1b837a1bd3a872808e7649865ef176cff6d6b0", "size": 21025, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Language/Grappa/Interp/StandardHORepr.hs", "max_stars_repo_name": "kquick/grappa", "max_stars_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-11-27T06:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T06:40:58.000Z", "max_issues_repo_path": "src/Language/Grappa/Interp/StandardHORepr.hs", "max_issues_repo_name": "kquick/grappa", "max_issues_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-09-05T16:06:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-26T01:24:32.000Z", "max_forks_repo_path": "src/Language/Grappa/Interp/StandardHORepr.hs", "max_forks_repo_name": "kquick/grappa", "max_forks_repo_head_hexsha": "44f22522a4cc64ed3c947466f0d06ce97403387c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-11-19T17:29:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T17:29:10.000Z", "avg_line_length": 37.0158450704, "max_line_length": 81, "alphanum_fraction": 0.6503686088, "num_tokens": 6489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.2942149783515163, "lm_q1q2_score": 0.17768579558019204}}
{"text": "{-# LANGUAGE DataKinds              #-}\n{-# LANGUAGE DeriveGeneric          #-}\n{-# LANGUAGE FlexibleContexts       #-}\n{-# LANGUAGE FlexibleInstances      #-}\n{-# LANGUAGE FunctionalDependencies #-}\n{-# LANGUAGE GADTs                  #-}\n{-# LANGUAGE LambdaCase             #-}\n{-# LANGUAGE MultiParamTypeClasses  #-}\n{-# LANGUAGE OverloadedStrings      #-}\n{-# LANGUAGE PolyKinds              #-}\n{-# LANGUAGE RankNTypes             #-}\n{-# LANGUAGE RecordWildCards        #-}\n{-# LANGUAGE ScopedTypeVariables    #-}\n{-# LANGUAGE TemplateHaskell        #-}\n{-# LANGUAGE TupleSections          #-}\n{-# LANGUAGE TypeApplications       #-}\n{-# LANGUAGE TypeFamilies           #-}\n{-# LANGUAGE TypeOperators          #-}\n{-# LANGUAGE TypeSynonymInstances   #-}\n\nmodule Egg.Vehicle (\n    Vehicle(..), vName, vBaseCapacity, vCosts\n  , VehicleData(..), HasVehicleData(..), SomeVehicleData\n  , DepotStatus(..), _DepotStatus, SomeDepotStatus, _SomeDepotStatus\n  , SomeVehicleUpgradeError(..), _SVUERegression, _SVUENoSlot\n  , withSomeDepotStatus\n  , initDepotStatus\n  , initSomeDepotStatus\n  , baseDepotCapacity\n  , totalDepotCapacity\n  , vehicleHistory\n  , vehicleCostAt\n  , vehiclePrice\n  , upgradeVehicle\n  , upgradeSomeVehicle\n  , vehicleUpgrades\n  , someVehicleUpgrades\n  ) where\n\nimport           Control.Applicative\nimport           Control.Lens hiding         ((.=))\nimport           Control.Monad\nimport           Data.Aeson\nimport           Data.Dependent.Sum\nimport           Data.Finite\nimport           Data.Finite.Internal\nimport           Data.Finite.Util            ()\nimport           Data.Functor\nimport           Data.Maybe\nimport           Data.Singletons\nimport           Data.Singletons.Prelude.Num\nimport           Data.Singletons.TypeLits\nimport           Data.Type.Combinator\nimport           Data.Vector.Sized.Util\nimport           Egg.Commodity\nimport           Egg.Research\nimport           GHC.Generics                (Generic)\nimport           Numeric.Lens\nimport           Numeric.Natural\nimport           Statistics.LinearRegression\nimport           Text.Printf\nimport qualified Data.Map                    as M\nimport qualified Data.Text                   as T\nimport qualified Data.Vector                 as V\nimport qualified Data.Vector.Sized           as SV\nimport qualified GHC.TypeLits                as TL\n\ndata Vehicle = Vehicle\n        { _vName         :: T.Text\n        , _vBaseCapacity :: Natural         -- ^ eggs per minute\n        , _vCosts        :: V.Vector Bock\n        , _vRegression   :: Maybe (Double, Double)\n        }\n  deriving (Show, Eq, Ord, Generic)\n\nmakeLenses ''Vehicle\n\nnewtype VehicleData vs = VehicleData { _vdVehicles :: SV.Vector vs Vehicle }\n  deriving (Show, Eq, Ord, Generic)\n\nmakeClassy ''VehicleData\nmakeWrapped ''VehicleData\n\ntype SomeVehicleData = DSum Sing VehicleData\n\ndata DepotStatus vs slots\n    = DepotStatus { _dsSlots :: M.Map (Finite slots) (Finite vs) }\n  deriving (Show, Eq, Ord, Generic)\n\nmakePrisms ''DepotStatus\nmakeWrapped ''DepotStatus\n\ndata SomeVehicleUpgradeError vs\n        = SVUERegression { _svuePrevious :: Finite vs }\n        | SVUENoSlot\n  deriving (Show, Eq, Ord)\n\nmakePrisms ''SomeVehicleUpgradeError\n\ndata SomeDepotStatus vs\n    = SomeDepotStatus { _sdsSlots :: M.Map Natural (Finite vs) }\n  deriving (Show, Eq, Ord, Generic)\n\n_SomeDepotStatus\n    :: Functor f\n    => Bonuses\n    -> (forall slots. KnownNat slots => LensLike' f (DepotStatus vs slots) b)\n    -> LensLike' f (SomeDepotStatus vs) b\n_SomeDepotStatus bs f g = traverseSomeDepotStatus bs (f g)\n\nwithSomeDepotStatus\n    :: Bonuses\n    -> SomeDepotStatus vs\n    -> (forall slots. KnownNat slots => DepotStatus vs slots -> r)\n    -> r\nwithSomeDepotStatus bs sd f = sd ^. _SomeDepotStatus bs (to f)\n\ntraverseSomeDepotStatus\n    :: Functor f\n    => Bonuses\n    -> (forall slots. KnownNat slots => DepotStatus vs slots -> f (DepotStatus vs slots))\n    -> SomeDepotStatus vs\n    -> f (SomeDepotStatus vs)\ntraverseSomeDepotStatus bs f sds0 = withSomeSing fleetSize $ \\(SNat :: Sing slots) ->\n    let ds0 = DepotStatus\n            . M.mapKeysMonotonic (Finite . fromIntegral)\n            . M.filterWithKey (\\k _ -> k < fleetSize)\n            $ _sdsSlots sds0\n    in  SomeDepotStatus . M.mapKeysMonotonic (fromIntegral . getFinite) . _dsSlots\n          <$> f @slots ds0\n  where\n    fleetSize :: Natural\n    fleetSize = 4 ^. bonusingFor @Double bs BTFleetSize . to round\n\nvehicleParseOptions :: Options\nvehicleParseOptions = defaultOptions\n    { fieldLabelModifier = camelTo2 '-' . drop 2\n    }\n\ninstance FromJSON Vehicle where\n    parseJSON  = fmap fillRegression . genericParseJSON  vehicleParseOptions\ninstance ToJSON Vehicle where\n    toJSON     = genericToJSON     vehicleParseOptions\n    toEncoding = genericToEncoding vehicleParseOptions\n\nfillRegression :: Vehicle -> Vehicle\nfillRegression v = case v ^. vRegression of\n    Just _  -> v\n    Nothing -> v & vRegression .~ reg\n  where\n    reg = guard (V.length c > 1) $>\n                 linearRegression (V.imap (\\i _ -> fromIntegral i) c)\n                                  (log . view bock <$> c)\n      where\n        c = v ^. vCosts\n\ninstance FromJSON SomeVehicleData where\n    parseJSON o = do\n      vs <- parseJSON o\n      SV.withSized vs $ \\vsV ->\n        return $ SNat :=> VehicleData vsV\ninstance ToJSON SomeVehicleData where\n    toJSON = \\case\n        _ :=> r -> toJSON r\n    toEncoding = \\case\n        _ :=> r -> toEncoding r\ninstance KnownNat vs => FromJSON (VehicleData vs) where\n    parseJSON o = do\n      vs <- parseJSON o\n      case SV.toSized vs of\n        Nothing  -> fail $ printf \"Bad number of items in list. (Expected %d, got %d)\"\n                         (fromSing (SNat @vs)) (length vs)\n        Just vsV -> return $ VehicleData vsV\ninstance ToJSON (VehicleData habs) where\n    toJSON     = toJSON     . SV.fromSized . _vdVehicles\n    toEncoding = toEncoding . SV.fromSized . _vdVehicles\n\ninstance (KnownNat vs, KnownNat slots) => FromJSON (DepotStatus vs slots) where\n    parseJSON o = DepotStatus <$> parseJSON o\ninstance ToJSON (DepotStatus vs slots) where\n    toJSON = toJSON . _dsSlots\n    toEncoding = toEncoding . _dsSlots\ninstance KnownNat vs => FromJSON (SomeDepotStatus vs) where\n    parseJSON o = SomeDepotStatus <$> parseJSON o\ninstance ToJSON (SomeDepotStatus vs) where\n    toJSON = toJSON . _sdsSlots\n    toEncoding = toEncoding . _sdsSlots\n\n-- | Initial 'DepotStatus' to start off the game.\ninitDepotStatus :: (KnownNat vs, KnownNat slots, 1 TL.<= vs, 1 TL.<= slots) => DepotStatus vs slots\ninitDepotStatus = DepotStatus $ M.singleton 0 0\n\n-- | Initial 'SomeDepotStatus' to start off the game.\ninitSomeDepotStatus :: (KnownNat vs, 1 TL.<= vs) => SomeDepotStatus vs\ninitSomeDepotStatus = SomeDepotStatus $ M.singleton 0 0\n\n-- | Total base capacity of all slots, in eggs per second.\nbaseDepotCapacity\n    :: forall vs slots. KnownNat vs\n    => VehicleData vs\n    -> DepotStatus vs slots\n    -> Double\nbaseDepotCapacity VehicleData{..} =\n    sumOf $ _DepotStatus\n          . folded\n          . to (SV.index _vdVehicles)\n          . vBaseCapacity\n          . to fromIntegral\n          . dividing 60\n\n-- | Total capacity of all vehicles, factoring in bonuses.\ntotalDepotCapacity\n    :: forall vs slots. KnownNat vs\n    => VehicleData vs\n    -> Bonuses\n    -> DepotStatus vs slots\n    -> Double\ntotalDepotCapacity vd@VehicleData{..} bs =\n    sumOf $ to (baseDepotCapacity vd)\n          . bonusingFor bs BTVehicleCapacity\n          . bonusingFor bs BTVehicleSpeed\n\n-- | How many of each vehicle has been purchased so far.  If key is not found,\n-- zero purchases is implied.\nvehicleHistory\n    :: KnownNat (slots TL.+ 1)\n    => DepotStatus vs slots\n    -> M.Map (Finite vs) (Finite (slots TL.+ 1))\nvehicleHistory = M.fromListWith (+)\n               . toListOf (_DepotStatus . folded . to (, 1))\n\n-- | Get the BASE price of a given vehicle, if a purchase were to be made.\n-- Does not check if purchase is legal (see 'upgradeVehicle').\n--\n-- Returns Nothing if slots are all full?\nvehiclePrice\n    :: forall vs slots. (KnownNat vs, KnownNat slots)\n    => VehicleData vs\n    -> DepotStatus vs slots\n    -> Finite vs\n    -> Maybe Bock\nvehiclePrice vd ds v = withKnownNat (SNat @slots %+ SNat @1) $\n                           fmap priceOf\n                         . strengthen\n                         . fromMaybe 0\n                         . M.lookup v\n                         . vehicleHistory\n                         $ ds\n  where\n    priceOf :: Finite slots -> Bock\n    priceOf i = vd ^. vdVehicles\n                    . ixSV v\n                    . to (vehicleCostAt (fromIntegral i))\n\nvehicleCostAt :: Int -> Vehicle -> Bock\nvehicleCostAt i v = fromMaybe 100 $\n        (v ^? vCosts . ix i) <|> (r <$> v ^. vRegression)\n  where\n    r (\u03b1, \u03b2) = realToFrac . exp $ \u03b1 + \u03b2 * fromIntegral i\n\n-- | Purchase a vehicle upgrade.  Returns cost and new depot status,\n-- if purchase is valid.\n--\n-- Purchase is invalid if purchasing a vehicle in a slot where a greater\n-- vehicle is already purchased.\nupgradeVehicle\n    :: (KnownNat vs, KnownNat slots)\n    => VehicleData vs\n    -> Bonuses\n    -> Finite slots\n    -> Finite vs\n    -> DepotStatus vs slots\n    -> Either (Finite vs) (Bock, DepotStatus vs slots)\nupgradeVehicle vd bs slot v ds0 =\n    getComp . flip (_DepotStatus . at slot) ds0 $ \\s0 -> Comp $ do\n      case s0 of\n        Just h | h >= v -> Left h\n        _               -> Right ()\n      -- should always be valid of the previous condition is true\n      let price = fromJust $ vehiclePrice vd ds0 v\n      return (price ^. bonusingFor bs BTVehicleCosts, Just v)\n\n-- | Purchase a vehicle upgrade.  Returns cost and new depot status,\n-- if purchase is valid.\n--\n-- Purchase is invalid if purchasing a vehicle in a slot where a greater\n-- vehicle is already purchased, and also if there is no such slot.\nupgradeSomeVehicle\n    :: forall vs. KnownNat vs\n    => VehicleData vs\n    -> Bonuses\n    -> Integer\n    -> Finite vs\n    -> SomeDepotStatus vs\n    -> Either (SomeVehicleUpgradeError vs) (Bock, SomeDepotStatus vs)\nupgradeSomeVehicle vd bs slot v sds0 =\n    getComp . traverseSomeDepotStatus bs (Comp . go) $ sds0\n  where\n    go  :: KnownNat slots\n        => DepotStatus vs slots\n        -> Either (SomeVehicleUpgradeError vs) (Bock, DepotStatus vs slots)\n    go ds0 = case packFinite slot of\n      Nothing    -> Left SVUENoSlot\n      Just slot' -> either (Left . SVUERegression) Right $\n                      upgradeVehicle vd bs slot' v ds0\n\n-- | List all possible vehicle upgrades.\n--\n-- Is a Left if the vehicle upgrade would be a regression.\nvehicleUpgrades\n    :: forall vs slots. KnownNat slots\n    => VehicleData vs\n    -> Bonuses\n    -> DepotStatus vs slots\n    -> (SV.Vector slots :.: SV.Vector vs :.: Either (Finite vs)) Bock\nvehicleUpgrades vd bs ds = Comp . Comp $ SV.generate go\n  where\n    slots1 = SNat @slots %+ SNat @1\n    hist :: M.Map (Finite vs) (Finite (slots TL.+ 1))\n    hist = withKnownNat slots1 $\n             vehicleHistory ds\n    go :: Finite slots -> SV.Vector vs (Either (Finite vs) Bock)\n    go s = vd ^. vdVehicles\n              & SV.imap\n                  (\\j h -> withKnownNat slots1 $ do\n                      case currVeh of\n                        Just v | v >= j -> Left v\n                        _               -> Right ()\n                      let n = M.findWithDefault 0 j hist\n                      return $ h ^. to (vehicleCostAt (fromIntegral n))\n                                  . bonusingFor bs BTVehicleCosts\n                  )\n      where\n        currVeh = ds ^? _DepotStatus . ix s\n\n-- | List all possible vehicle upgrades for a 'SomeDepotStatus'.\n--\n-- Is a Left if the vehicle upgrade would be a regression.\nsomeVehicleUpgrades\n    :: forall vs. ()\n    => VehicleData vs\n    -> Bonuses\n    -> SomeDepotStatus vs\n    -> (V.Vector :.: SV.Vector vs :.: Either (Finite vs)) Bock\nsomeVehicleUpgrades vd bs = view $ _SomeDepotStatus bs go\n                                 . _Unwrapped\n                                 . _Unwrapped\n  where\n    go  :: KnownNat slots\n        => Getter (DepotStatus vs slots)\n                  (V.Vector (SV.Vector vs (Either (Finite vs) Bock)))\n    go = to (vehicleUpgrades vd bs)\n       . _Wrapped\n       . _Wrapped\n       . to SV.fromSized\n", "meta": {"hexsha": "96e215a36933f3914dd3445014f734e266217da6", "size": 12253, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Egg/Vehicle.hs", "max_stars_repo_name": "mstksg/eggvisor", "max_stars_repo_head_hexsha": "9bca62aef60de85e0d30fccf7b2926962979c352", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2017-05-31T17:40:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T07:53:49.000Z", "max_issues_repo_path": "src/Egg/Vehicle.hs", "max_issues_repo_name": "mstksg/eggvisor", "max_issues_repo_head_hexsha": "9bca62aef60de85e0d30fccf7b2926962979c352", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Egg/Vehicle.hs", "max_forks_repo_name": "mstksg/eggvisor", "max_forks_repo_head_hexsha": "9bca62aef60de85e0d30fccf7b2926962979c352", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-08-18T14:06:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-18T14:06:45.000Z", "avg_line_length": 34.4185393258, "max_line_length": 99, "alphanum_fraction": 0.6197665878, "num_tokens": 3136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.29746993014852224, "lm_q1q2_score": 0.1774209263576015}}
{"text": "{-# LANGUAGE GADTs #-}\nmodule Format.FastTime\n  ( FastTime()\n  , fastTime\n  , ignoreHigh\n  ) where\n\nimport Data.Time.Clock\nimport Statistics.Distribution\nimport Statistics.Distribution.Normal\nimport Text.Printf\n\nnewtype FastTime where\n  FastTime :: Double -> FastTime\n\ninstance Show FastTime where\n  showsPrec _ = showFastTime\n\n\nfastTime :: NominalDiffTime -> FastTime\nfastTime = FastTime . realToFrac\n\n\nshowFastTime :: FastTime -> ShowS\nshowFastTime (FastTime p) = showString go\n  where go | p <= (-1000) = replicate 4 '\\8593'\n           | p >=      0  = replicate 4 '-'\n           | p <=   (-10) = printf \"-%3.0f\" $ abs p\n           | otherwise    = printf \"%4.1f\" p\n\nignoreHigh :: FastTime -> String\nignoreHigh a = go $ calc a\n  where go p | p <= (-10) = \"   \"\n             | otherwise  = show a\n\n\ncalc :: FastTime -> Double\ncalc (FastTime t) = undefined\n", "meta": {"hexsha": "2a576265a5990b4ac89a7b6d629c4086cc5a70ec", "size": 858, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Format/FastTime.hs", "max_stars_repo_name": "argiopetech/timer", "max_stars_repo_head_hexsha": "1962af91004cddb0e2409a5089164eb343e7eb2e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Format/FastTime.hs", "max_issues_repo_name": "argiopetech/timer", "max_issues_repo_head_hexsha": "1962af91004cddb0e2409a5089164eb343e7eb2e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2018-01-29T16:51:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-29T16:51:58.000Z", "max_forks_repo_path": "src/Format/FastTime.hs", "max_forks_repo_name": "argiopetech/timer", "max_forks_repo_head_hexsha": "1962af91004cddb0e2409a5089164eb343e7eb2e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0, "max_line_length": 51, "alphanum_fraction": 0.6351981352, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.17390068230595473}}
{"text": "{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE RecordWildCards #-}\n\nmodule Main where\nimport Debug.Trace (traceShow)\nimport Data.Either.Combinators (fromRight, maybeToRight)\nimport BDSCOD.Llhd (llhdAndNB,initLlhdState, intervalLlhd)\nimport BDSCOD.Types\nimport BDSCOD.Utility\nimport Control.Monad (zipWithM)\nimport Control.Monad.Except (ExceptT, runExceptT, throwError)\nimport Control.Monad.Reader (ReaderT, asks, liftIO, runReaderT)\nimport qualified Data.Aeson as Json\nimport qualified Data.ByteString.Builder as BBuilder\nimport qualified Data.ByteString.Lazy as L\nimport qualified Data.Csv as Csv\nimport Data.List (intercalate, intersperse,nub)\nimport Data.Maybe (fromMaybe)\nimport qualified Data.Vector.Unboxed as Unboxed\nimport qualified Epidemic.BDSCOD as SimBDSCOD\nimport Epidemic.Types.Events\n  ( EpidemicEvent(..)\n  , asNewickString\n  , eventTime\n  , maybeEpidemicTree\n  , maybeReconstructedTree\n  )\nimport Epidemic.Types.Parameter\nimport Epidemic.Types.Population (Person(..), Identifier(..))\nimport qualified Epidemic.Utility as SimUtil\nimport GHC.Generics\nimport Numeric.Minimisation.Powell (minimise)\nimport Numeric.LinearAlgebra.Data (linspace, toList)\nimport Numeric.LinearAlgebra.HMatrix\nimport System.Environment (getArgs)\nimport System.Random.MWC\nimport Data.Word (Word32)\nimport System.IO.Unsafe (unsafePerformIO)\n\n\n-- | Values of this type are used to specify an analysis of the data.\ndata InferenceConfiguration =\n  InferenceConfiguration\n    {\n    -- | The time in the simulation at which the inference is carried out.\n    inferenceTime :: AbsoluteTime\n    ,\n    -- | A couple of files to write the Newick representation to and the node labels.\n    reconstructedTreeOutputFiles :: (FilePath, FilePath)\n    ,\n    -- | Where to write the sequence of observed events.\n    observationsOutputCsv :: FilePath\n    ,\n    -- | Where to write the likelihood evaluations.\n    llhdOutputCsv :: FilePath\n    ,\n    -- | Where to write the point estimate of prevalence.\n    pointEstimatesCsv :: FilePath\n    }\n  deriving (Show, Generic)\n\n-- | These objects describe the evaluation mesh when looking at the likelihood\n-- profiles. This is useful because it allows us to provide these details at\n-- runtime rather than hardcoding them here.\ndata LlhdProfileMesh =\n  LlhdProfileMesh\n  { lpmMeshSize :: Int\n  , lpmLambdaBounds :: (Rate,Rate)\n  , lpmMuBounds :: (Rate,Rate)\n  , lpmPsiBounds :: (Rate,Rate)\n  , lpmRhoBounds :: (Probability,Probability)\n  , lpmOmegaBounds :: (Rate,Rate)\n  , lpmNuBounds :: (Probability,Probability)\n  } deriving (Show, Generic)\n\n-- | This object configures the whole evaluation of this program and is to be\n-- read in from a suitable JSON file.\ndata AppConfiguration =\n  AppConfiguration\n    { simulatedEventsOutputCsv :: FilePath\n    , simulationParameters :: Parameters\n    , simulationDuration :: TimeDelta\n    , simulationSizeBounds :: (Int,Int)\n    , simulationSeed :: Word32\n    , inferenceConfigurations :: [InferenceConfiguration]\n    , acLlhdProfileMesh :: LlhdProfileMesh\n    }\n  deriving (Show, Generic)\n\ninstance Json.FromJSON AppConfiguration\n\ninstance Json.FromJSON InferenceConfiguration\n\ninstance Json.FromJSON LlhdProfileMesh\n\ntype Simulation x = ReaderT AppConfiguration (ExceptT String IO) x\n\n-- | This type is used to indicate if parameters are the true ones used in the\n-- simulation or estimates parameters.\ndata ParameterKind\n  = SimulationParameters\n  | EstimatedParameters\n  deriving (Show, Eq)\n\n-- | A BDSCOD simulation configuration based on the parameters in the\n-- environment.\nbdscodConfiguration = do\n  simParams <- asks simulationParameters\n  (TimeDelta simDurDouble) <- asks simulationDuration\n  let bdscodConfig =\n        SimBDSCOD.configuration (AbsoluteTime simDurDouble) (unpackParameters simParams)\n  case bdscodConfig of\n    Just x -> do liftIO $ putStrLn (show simParams)\n                 return x\n    Nothing -> throwError \"Could not construct BDSCOD configuration\"\n\n-- | Simulate the transmission process part of the epidemic making sure that the\n-- results are acceptable in terms of the number of observed events before\n-- returning a filtration of the events, i.e., the data that was availble at\n-- several points in time.\n--\n-- __NOTE__ the filteration must happen before these are processed into\n-- observations since the observations do not accumulate chronologically due to\n-- birth events which can occur in the past due to new observations in the\n-- present.\npartialSimulatedEpidemic seedWord bdscodConfig =\n  do\n    gen <- liftIO $ initialize (Unboxed.fromList [seedWord])\n    simEvents <- liftIO $ SimUtil.simulation' bdscodConfig SimBDSCOD.allEvents gen\n    (sizeLowerBound,sizeUpperBound) <- asks simulationSizeBounds\n    if length simEvents > sizeLowerBound && length simEvents < sizeUpperBound\n      then do infTimes <- map inferenceTime <$> asks inferenceConfigurations\n              simEventsCsv <- asks simulatedEventsOutputCsv\n              liftIO $ L.writeFile simEventsCsv (Csv.encode simEvents)\n              return [filter (\\e -> eventTime e <= infTime) simEvents | infTime <- infTimes]\n      else do liftIO $ putStrLn \"Repeating epidemic simulation...\"\n              partialSimulatedEpidemic (seedWord + 1) bdscodConfig\n\n-- | Run the actual observation of the simulation and record the results before\n-- returning the dataset of observations generated by this epidemic.\nsimulatedObservations :: InferenceConfiguration\n                      -> [EpidemicEvent]\n                      -> Simulation (InferenceConfiguration,[Observation])\nsimulatedObservations infConfig@InferenceConfiguration{..} simEvents = do\n  let Just (newickBuilder,newickMetaData) =\n        do eTree <- maybeEpidemicTree simEvents\n           rTree <- maybeReconstructedTree eTree\n           asNewickString (AbsoluteTime 0, Person (Identifier 1)) rTree\n      maybeObs = eventsAsObservations <$> SimBDSCOD.observedEvents simEvents\n      (reconNewickTxt,reconNewickCsv) = reconstructedTreeOutputFiles\n  case maybeObs of\n    (Just obs) ->\n      do\n        liftIO $ L.writeFile reconNewickTxt (BBuilder.toLazyByteString newickBuilder)\n        liftIO $ L.writeFile reconNewickCsv (Csv.encode newickMetaData)\n        liftIO $ L.writeFile observationsOutputCsv (Csv.encode obs)\n        return (infConfig,obs)\n    _ -> throwError \"Failed to simulate observations.\"\n\n\n-- | If there is a unique timed value return that. This is used to make it\n-- easier to extract the values of timed parameters so that you don't need to\n-- store all of them.\nuniqueTimedValue :: Eq x => Timed x -> Maybe x\nuniqueTimedValue (Timed txs) = case txs of\n  [] -> Nothing\n  txs' -> let xs = nub [snd tx | tx <- txs']\n              isUnique = 1 == length xs\n            in if isUnique then Just (head xs) else Nothing\n\n-- | Evaluate the NB posterior approximation of the prevalence for a single\n-- point in parameter space and the LLHD over a list of points and write all of\n-- the results to CSV.\nrecordLlhdCrossSections :: InferenceConfiguration\n                          -> [Observation]\n                          -> (Parameters,ParameterKind,[Parameters])\n                          -> Simulation ()\nrecordLlhdCrossSections InferenceConfiguration {..} obs (singleParams, paramKind, evalParams) =\n  let comma = BBuilder.charUtf8 ','\n      parametersUsed = show paramKind\n      parametersUsed' = BBuilder.stringUtf8 parametersUsed\n      llhdVals = safeLlhdFromInit obs <$> evalParams\n      nBValAndParams =\n        Csv.encode . (:[]) $\n        ( parametersUsed\n        , show $ length obs\n        , fromRight Zero $ snd <$> llhdAndNB obs singleParams initLlhdState\n        , show $ getLambda singleParams\n        , show $ getMu singleParams\n        , show $ getPsi singleParams\n        , show <$> uniqueTimedValue $ getRhos singleParams\n        , show $ getOmega singleParams\n        , show <$> uniqueTimedValue $ getNus singleParams )\n      doublesAsString =\n        BBuilder.toLazyByteString .\n        mconcat .\n        intersperse comma . (parametersUsed' :) . map BBuilder.doubleDec\n   in liftIO $\n      do\n        L.appendFile llhdOutputCsv (doublesAsString llhdVals)\n        L.appendFile pointEstimatesCsv nBValAndParams\n\n-- | Evaluate the LLHD function on cross-sections centred at the true values\nevaluateLLHD :: InferenceConfiguration -> [Observation] -> Simulation ()\nevaluateLLHD infConfig obs = do\n  simParams <- asks simulationParameters -- get the actual parameters used to simulate the observations\n  llhdProfMesh <- asks acLlhdProfileMesh -- this specifies the cross section to use.\n  let evalParams = crossSectionParameters llhdProfMesh simParams\n  recordLlhdCrossSections infConfig obs (simParams,SimulationParameters,evalParams)\n\n-- | Estimate the parameters of the of the model and then evaluate the LLHD\n-- profiles and prevalence and append this to the file. The first value of the\n-- CSV output now describes which parameters where used to to evaluate these\n-- things.\nestimateLLHD :: InferenceConfiguration -> [Observation] -> Simulation ()\nestimateLLHD infConfig obs = do\n  simParams@(Parameters (_,deathRate,_,_,_,_)) <- asks simulationParameters\n  llhdProfMesh <- asks acLlhdProfileMesh\n  liftIO $ putStrLn $ \"\\t\\tEstimating parameters using \" ++ show (length obs) ++ \" observations...\"\n  let schedTimes = scheduledTimes simParams\n      mleParams = estimateParameters deathRate schedTimes obs -- get the MLE estimate of the parameters\n      evalParams = crossSectionParameters llhdProfMesh mleParams\n  recordLlhdCrossSections infConfig obs (mleParams,EstimatedParameters,evalParams)\n\n-- | A safe version of the log-likelihood assuming that you want to start from a\n-- simple initial condition.\n--\n-- __NOTE__ This conditions the process against extinction.\n--\nsafeLlhdFromInit :: [Observation] -> Parameters -> LogLikelihood\nsafeLlhdFromInit obs p@(Parameters (\u03bb, \u03bc, \u03c8, _, \u03c9, _)) =\n    let\n      -- log-likelihood\n      llhd = fromRight (-1e6) $ fst <$> llhdAndNB obs p initLlhdState\n      -- log of the probability of not going extinct.\n      lpne = log (1 - (\u03bc + \u03c8 + \u03c9) / \u03bb)\n    in llhd - lpne\n\n-- | Estimate of the MLE. This uses a simplex method.\n--\n-- __NOTE__ the ugly case statement means that this should work both with and\n-- without scheduled observations.\n--\n-- __NOTE__ we fix the death rate to the true value because\n-- this is assumed to be known a priori.\n--\nestimateParameters :: Rate -> ([AbsoluteTime],[AbsoluteTime]) -> [Observation] -> Parameters\nestimateParameters deathRate sched obs =\n  let energyFunc v2p x =\n        negate $ safeLlhdFromInit obs (v2p x)\n      mini rI v2p = minimise (energyFunc v2p) rI\n  in case sched of\n       -- there are no scheduled observations\n       ([],[]) ->\n         let -- randInit = [-1.5,-2.2,-2.2] -- initial point to start\n           randInit = log <$> [0.228,4.8e-2,2.6e-2] -- _GROSS_ initial point as true value\n           vec2Param vec =\n             let [lnR1, lnR2, lnR3] = vec\n             in packParameters ( exp lnR1\n                               , deathRate\n                               , exp lnR2\n                               , []\n                               , exp lnR3\n                               , [])\n         in case mini randInit vec2Param of\n              Right (est,_,grad) -> traceShow grad $ vec2Param est\n              Left msg -> error msg\n       -- there is at least one scheduled observation\n       (rhoTs, nuTs) ->\n         let randInit = [-1.5,-2.5,-1,-2.5,-1]\n             vec2Param vec =\n               let [lnR1, lnR2, logitP1, lnR3, logitP2] = vec\n                   rhoVal = invLogit logitP1\n                   nuVal = invLogit logitP2\n                   timed v ts = zip ts (repeat v)\n               in packParameters ( exp lnR1\n                                 , deathRate\n                                 , exp lnR2\n                                 , timed rhoVal rhoTs\n                                 , exp lnR3\n                                 , timed nuVal nuTs)\n         in case mini randInit vec2Param of\n              Right (est,_,grad) -> traceShow grad $ vec2Param est\n              Left msg -> error msg\n\n\n-- | List of parameters required to plot the cross sections.\ncrossSectionParameters :: LlhdProfileMesh -> Parameters -> [Parameters]\ncrossSectionParameters LlhdProfileMesh{..} ps =\n  let mesh = toList . linspace lpmMeshSize\n      lambdaMesh = mesh lpmLambdaBounds\n      muMesh = mesh lpmMuBounds\n      psiMesh = mesh lpmPsiBounds\n      rhoProbMesh = mesh lpmRhoBounds\n      omegaMesh = mesh lpmOmegaBounds\n      nuProbMesh = mesh lpmNuBounds\n      (rhoTimes,nuTimes) = scheduledTimes ps\n      rhoMesh = [Timed [(t,r) | t <- rhoTimes] | r <- rhoProbMesh]\n      nuMesh = [Timed [(t,n) | t <- nuTimes] | n <- nuProbMesh]\n      -- for each dimension, construct a list of parameter values with the\n      -- values from the mesh\n      apply f = map (f ps)\n      [lPs,mPs,pPs,oPs] =\n        zipWith apply [putLambda,putMu,putPsi,putOmega] [lambdaMesh,muMesh,psiMesh,omegaMesh]\n      [rPs,nPs] = zipWith apply [putRhos,putNus] [rhoMesh,nuMesh]\n  in concat $\n     if (rhoTimes,nuTimes) /= ([],[])\n     then [lPs,mPs,pPs,rPs,oPs,nPs]\n     else [lPs,mPs,pPs,oPs]\n\n-- | Definition of the complete simulation study.\nsimulationStudy :: Simulation ()\nsimulationStudy = do\n  bdscodConfig <- bdscodConfiguration\n  liftIO $ putStrLn \"\\tRunning epidemic simulation\"\n  simSeed <- asks simulationSeed\n  pEpi <- partialSimulatedEpidemic simSeed bdscodConfig\n  infConfigs <- asks inferenceConfigurations\n  liftIO $ putStrLn \"\\tExtracting observations from full simulation\"\n  pObs <- zipWithM simulatedObservations infConfigs pEpi\n  liftIO $ putStrLn \"\\tEvaluating LLHD on cross-sections about true parameters\"\n  mapM_ (uncurry evaluateLLHD) pObs\n  liftIO $ putStrLn \"\\tEvaluating LLHD on cross-sections about estimated parameters\"\n  mapM_ (uncurry estimateLLHD) pObs\n\n\n\nmain' :: IO ()\nmain' = do\n  let configFilePath = \"./examples/simulation-study-time-series/ts-config.json\"\n  maybeConfig <- getConfiguration configFilePath\n  case maybeConfig of\n    Nothing ->\n      putStrLn $ \"Could not get configuration from file: \" ++ configFilePath\n    Just config -> do\n      putStrLn $ \"Succeeded in reading configuration from file: \" ++ configFilePath\n      result <- runExceptT (runReaderT simulationStudy config)\n      case result of\n        Left errMsg -> putStrLn errMsg\n        Right _ -> return ()\n\nmain :: IO ()\nmain = do\n  configFilePath <- head <$> getArgs\n  maybeConfig <- getConfiguration configFilePath\n  case maybeConfig of\n    Nothing ->\n      putStrLn $ \"Could not get configuration from file: \" ++ configFilePath\n    Just config -> do\n      putStrLn $ \"Succeeded in reading configuration from file: \" ++ configFilePath\n      result <- runExceptT (runReaderT simulationStudy config)\n      case result of\n        Left errMsg -> putStrLn errMsg\n        Right _ -> return ()\n\n-- | Attempt to read a configuration object from the given filepath.\ngetConfiguration :: FilePath -> IO (Maybe AppConfiguration)\ngetConfiguration fp = Json.decode <$> L.readFile fp\n", "meta": {"hexsha": "1789ea427cfb23c9339689dd203e315e5be89957", "size": 15084, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "apps/simulation-study-time-series/Main.hs", "max_stars_repo_name": "aezarebski/timtam", "max_stars_repo_head_hexsha": "dc0f00a0196045bbc60d81a33a217e5d8e79e489", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-02-21T01:07:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T01:07:59.000Z", "max_issues_repo_path": "apps/simulation-study-time-series/Main.hs", "max_issues_repo_name": "aezarebski/timtam", "max_issues_repo_head_hexsha": "dc0f00a0196045bbc60d81a33a217e5d8e79e489", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-02-21T01:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-21T01:19:37.000Z", "max_forks_repo_path": "apps/simulation-study-time-series/Main.hs", "max_forks_repo_name": "aezarebski/timtam", "max_forks_repo_head_hexsha": "dc0f00a0196045bbc60d81a33a217e5d8e79e489", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.783933518, "max_line_length": 103, "alphanum_fraction": 0.6937814903, "num_tokens": 3663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.2845759981489974, "lm_q1q2_score": 0.1729263490496792}}
{"text": "{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nmodule Taiji.Pipeline.SC.ATACSeq.Functions.Feature.Peak\n    ( mkFeatMat\n    , mkPeakMat\n    , findPeaks\n    , mergePeaks\n    , getPeakEnrichment\n    , mkCellClusterBed\n    , computePeakRAS\n    ) where\n\nimport Control.Arrow (first)\nimport           Bio.Pipeline\nimport qualified Data.HashSet as S\nimport Bio.Data.Bed hiding (NarrowPeak)\nimport qualified Bio.Data.Bed as Bed\nimport Data.Conduit.Internal (zipSinks, zipSources)\nimport qualified Data.Text as T\nimport qualified Data.ByteString.Char8 as B\nimport qualified Data.Matrix as Mat\nimport Data.Singletons.Prelude (SingI)\nimport Shelly hiding (FilePath)\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Unboxed as U\nimport Control.DeepSeq (force)\nimport Data.Conduit.Zlib (gzip)\n\nimport Statistics.Distribution (quantile)\nimport Statistics.Distribution.ChiSquared (chiSquared)\n\nimport Taiji.Prelude\nimport Taiji.Pipeline.SC.ATACSeq.Types\nimport Taiji.Pipeline.SC.ATACSeq.Functions.Utils\nimport Taiji.Pipeline.SC.ATACSeq.Functions.QC (streamTN5Insertion)\nimport qualified Taiji.Utils.DataFrame as DF\nimport Taiji.Utils\n\n-- | Make the read count matrix.\nmkPeakMat :: SCATACSeqConfig config\n          => FilePath\n          -> SCATACSeq S (TagsAligned, File '[Gzip] 'NarrowPeak)\n          -> ReaderT config IO (SCATACSeq S (File '[Gzip] 'Matrix))\nmkPeakMat dir input = do\n    passedQC <- getQCFunction\n    let output = printf \"%s/%s_rep%d_peak.mat.gz\" dir (T.unpack $ input^.eid)\n            (input^.replicates._1)\n    input & replicates.traverse.files %%~ liftIO . (\\(tagFl, regionFl) -> do\n        regions <- runResourceT $ runConduit $\n            streamBedGzip (regionFl^.location) .| sinkList :: IO [BED3]\n        runResourceT $ runConduit $ streamTN5Insertion passedQC tagFl .|\n            mapC (\\xs -> (fromJust $ head xs^.name, xs)) .| mkCountMat regions .|\n            sinkRows' (length regions) (fromJust . packDecimal) output\n        return $ emptyFile & location .~ output )\n\n-- | Make the read count matrix.\nmkFeatMat :: SCATACSeqConfig config\n          => FilePath\n          -> SCATACSeq S (TagsAligned, File '[Gzip] 'NarrowPeak)\n          -> ReaderT config IO ( SCATACSeq S\n              ( File '[RowName, Gzip] 'Tsv\n              , File '[ColumnName, Gzip] 'Tsv\n              , File '[Gzip] 'Matrix ))\nmkFeatMat dir input = do\n    passedQC <- getQCFunction\n    let output = printf \"%s/%s_rep%d_peak.mat.gz\" dir (T.unpack $ input^.eid)\n            (input^.replicates._1)\n        rownames = printf \"%s/%s_rep%d_rownames.txt.gz\" dir (T.unpack $ input^.eid)\n            (input^.replicates._1)\n        features = printf \"%s/%s_rep%d_features.txt.gz\" dir (T.unpack $ input^.eid)\n            (input^.replicates._1)\n        bcPrefix = B.pack $ T.unpack (input^.eid) <> \"_\" <> show (input^.replicates._1) <> \"+\"\n    input & replicates.traverse.files %%~ liftIO . (\\(tagFl, regionFl) -> do\n        regions <- runResourceT $ runConduit $\n            streamBedGzip (regionFl^.location) .| sinkList :: IO [BED3]\n        let rowSink = mapC f .| unlinesAsciiC .| gzip .| sinkFile rownames\n              where\n                f (nm, xs) = force $ nm <> \"\\t\" <> fromJust (packDecimal $ foldl1' (+) $ map snd xs)\n            colSink = do\n                vec <- colSumC $ length regions\n                let bs = B.unlines $ zipWith showBed regions $ U.toList vec\n                yield bs .| gzip .| sinkFile features\n            showBed (BED3 chr s e) x = B.concat\n                [ chr, \":\", fromJust $ packDecimal s, \"-\"\n                , fromJust $ packDecimal e, \"\\t\", fromJust $ packDecimal x]\n            sink = (,,) <$> ZipSink (sinkRows' (length regions) (fromJust . packDecimal) output)\n                <*> ZipSink rowSink <*> ZipSink colSink\n        _ <- runResourceT $ runConduit $ streamTN5Insertion passedQC tagFl .|\n            mapC (\\xs -> (fromJust $ head xs^.name, xs)) .|\n            mkCountMat regions .| mapC (first (bcPrefix <>)) .|\n            getZipSink sink\n        return ( location .~ rownames $ emptyFile\n               , location .~ features $ emptyFile\n               , location .~ output $ emptyFile )\n        )\n        \n-- | Call Peaks for aggregated files\nfindPeaks :: (SingI tags, SCATACSeqConfig config)\n          => FilePath\n          -> CallPeakOpts\n          -> (B.ByteString, File tags 'Bed)\n          -> ReaderT config IO (B.ByteString, File '[Gzip] 'NarrowPeak)\nfindPeaks prefix opts (cName, bedFl) = do\n    tmpdir <- asks _scatacseq_tmp_dir\n    dir <- asks _scatacseq_output_dir >>= getPath . (<> asDir prefix)\n    let output = dir ++ \"/\" ++ B.unpack cName ++ \".narrowPeak.gz\" \n    asks _scatacseq_blacklist >>= \\case\n        Nothing -> liftIO $ do\n            r <- callPeaks output bedFl Nothing opts\n            return (cName, r)\n        Just blacklist -> liftIO $ withTemp tmpdir $ \\tmp -> do\n            _ <- callPeaks tmp bedFl Nothing opts\n            blackRegions <- readBed blacklist :: IO [BED3]\n            let bedTree = bedToTree const $ map (\\x -> (x, ())) blackRegions\n            runResourceT $ runConduit $\n                (streamBedGzip tmp :: ConduitT () Bed.NarrowPeak (ResourceT IO) ()) .|\n                filterC (not . isIntersected bedTree) .| sinkFileBedGzip output\n            return (cName, location .~ output $ emptyFile)\n\n-- | Merge peaks\nmergePeaks :: SCATACSeqConfig config\n           => FilePath\n           -> [(B.ByteString, File '[Gzip] 'NarrowPeak)]\n           -> ReaderT config IO (Maybe (File '[Gzip] 'NarrowPeak))\nmergePeaks _ [] = return Nothing\nmergePeaks dir input = do\n    tmpdir <- asks _scatacseq_tmp_dir\n    let output = dir <> \"/merged.narrowPeak.gz\" \n    liftIO $ withTemp tmpdir $ \\tmp1 -> withTemp tmpdir $ \\tmp2 -> do\n        runResourceT $ runConduit $ mapM_ (streamBedGzip . (^._2.location)) input .|\n            mapC resize .| sinkFileBed tmp1\n        shelly $ escaping False $ bashPipeFail bash_ \"cat\" $\n            [T.pack tmp1, \"|\", \"sort\", \"-k1,1\", \"-k2,2n\", \"-k3,3n\", \">\", T.pack tmp2]\n        let source = streamBed tmp2 .|\n                mergeSortedBedWith iterativeMerge .| concatC\n        runResourceT $ runConduit $ zipSources (iterateC succ (0 :: Int)) source .|\n            mapC (\\(i, p) -> name .~ Just (\"p\" <> B.pack (show i)) $ p) .|\n            sinkFileBedGzip output\n    return $ Just $ location .~ output $ emptyFile\n  where\n    iterativeMerge [] = []\n    iterativeMerge peaks = bestPeak : iterativeMerge rest\n      where\n        rest = filter (\\x -> sizeOverlapped x bestPeak == 0) peaks\n        bestPeak = maximumBy (comparing (fromJust . (^.npPvalue))) peaks\n    resize pk = chromStart .~ max 0 (summit - halfWindowSize) $\n        chromEnd .~ summit + halfWindowSize$\n        npPeak .~ Just halfWindowSize $ pk\n      where\n        summit = pk^.chromStart + fromJust (pk^.npPeak)\n    halfWindowSize = 200\n    \n-- | Extract BEDs for each cluster.\nmkCellClusterBed :: SCATACSeqConfig config\n                 => SCATACSeq S ( File '[NameSorted, Gzip] 'Bed\n                                , [CellCluster] )  -- ^ clusters\n                 -> ReaderT config IO\n                    (SCATACSeq S [(B.ByteString, File '[Gzip] 'Bed, Int)])\nmkCellClusterBed input = do\n    let idRep = asDir $ \"/Bed/\" <> T.unpack (input^.eid) <>\n            \"_rep\" <> show (input^.replicates._1)\n    dir <- asks _scatacseq_output_dir >>= getPath . (<> idRep)\n    input & replicates.traverse.files %%~ liftIO . ( \\(bed, cs) -> do\n        let sinks = sequenceConduits $ flip map cs $ \\CellCluster{..} -> do\n                let output = dir ++ \"/\" ++ B.unpack _cluster_name ++ \".bed.gz\"\n                    cells = S.fromList $ map _cell_barcode _cluster_member\n                    fl = location .~ output $ emptyFile\n                (_, depth) <- filterC (f cells) .|\n                    zipSinks (sinkFileBedGzip output) lengthC\n                return (_cluster_name, fl, depth)\n        runResourceT $ runConduit $\n            streamBedGzip (bed^.location) .| sinks )\n  where\n    f :: S.HashSet B.ByteString -> BED -> Bool\n    f cells x = fromJust (x^.name) `S.member` cells\n\n-- | Get signal enrichment for each peak\ngetPeakEnrichment :: SCATACSeqConfig config\n                  => ( [(B.ByteString, File '[Gzip] 'NarrowPeak)]\n                     , Maybe (File '[Gzip] 'NarrowPeak) )\n                  -> ReaderT config IO (File '[] 'Tsv, File '[] 'Tsv)\ngetPeakEnrichment (peaks, Just refPeak) = do\n    dir <- asks _scatacseq_output_dir >>= getPath . (<> \"/Feature/Peak/\")\n    let output1 = dir <> \"peak_signal.tsv\"\n        output2 = dir <> \"peak_pvalue.tsv\"\n    liftIO $ do\n        list <- runResourceT $ runConduit $\n            streamBedGzip (refPeak^.location) .| sinkList\n        let col = map toString list\n        (row, val) <- fmap unzip $ forM peaks $ \\(nm, p) -> do\n            peak <- runResourceT $ runConduit $ streamBedGzip (p^.location) .| sinkList\n            return (T.pack $ B.unpack nm, getValue peak list)\n        let (signal, pval) = DF.unzip $ DF.transpose $ DF.mkDataFrame row col val\n        DF.writeTable output1 (T.pack . show) signal\n        DF.writeTable output2 (T.pack . show) pval\n        return (location .~ output1 $ emptyFile, location .~ output2 $ emptyFile)\n  where\n    toString x = T.pack (B.unpack $ x^.chrom) <> \":\" <>\n        T.pack (show $ x^.chromStart) <> \"-\" <> T.pack (show $ x^.chromEnd)\n    getValue :: [Bed.NarrowPeak]  -- ^ query\n            -> [BED3]  -- ^ Peak list\n            -> [(Double, Double)]\n    getValue query peakList = runIdentity $ runConduit $\n        yieldMany peakList .| intersectBedWith f query .| sinkList\n      where\n        f _ [] = (0, 0)\n        f _ [x] = (x^.npSignal, quantile (chiSquared 1) $ 10**(negate $ fromJust $ x^.npPvalue))\n        f _ _ = undefined\ngetPeakEnrichment _ = undefined\n\n-- | Compute the relative accessibility score.\ncomputePeakRAS :: SCATACSeqConfig config\n               => FilePath\n               -> ( Maybe (File '[Gzip] 'NarrowPeak)\n                  , [SCATACSeq S (File '[Gzip] 'Matrix)] )\n               -> ReaderT config IO (Maybe (FilePath, FilePath, FilePath))\ncomputePeakRAS _ (Nothing, _) = return Nothing\ncomputePeakRAS prefix (peakFl, inputs) = do\n    dir <- asks ((<> asDir prefix) . _scatacseq_output_dir) >>= getPath\n    let output1 = dir <> \"relative_accessibility_scores.tsv\"\n        output2 = dir <> \"cell_specificity_score.tsv\"\n        output3 = dir <> \"/cell_specificity_pvalue.tsv\"\n    liftIO $ do\n        peaks <- fmap (map mkName) $ runResourceT $ runConduit $\n            streamBedGzip (fromJust peakFl^.location) .| sinkList\n\n        (names, cols) <- fmap unzip $ forM inputs $ \\input -> do\n            vec <- computeRAS (input^.replicates._2.files.location)\n            return (input^.eid, V.convert vec)\n\n        let ras = DF.map (*2.5) $ DF.fromMatrix peaks names $ Mat.fromColumns cols\n            ss = computeSS $ DF.map (logBase 2 . (+1)) ras\n        DF.writeTable output1 (T.pack . show) ras\n        DF.writeTable output2 (T.pack . show) ss\n        cdf <- computeCDF $ DF.map (logBase 2 . (+1)) ras\n        DF.writeTable output3 (T.pack . show) $ DF.map (lookupP cdf) ss\n        return $ Just (output1, output2, output3)\n  where\n    mkName :: BED3 -> T.Text\n    mkName p = T.pack $ B.unpack (p^.chrom) <> \":\" <> show (p^.chromStart) <>\n        \"-\" <> show (p^.chromEnd)\n    lookupP (vec, res, n) x | p == 0 = 1 / n\n                            | otherwise = p\n      where\n        p = vec V.! i\n        i = min (V.length vec - 1) $ truncate $ x / res ", "meta": {"hexsha": "21f0c78cd15f49e42bbd56a1eb74bbaccec0167d", "size": 11609, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Taiji/Pipeline/SC/ATACSeq/Functions/Feature/Peak.hs", "max_stars_repo_name": "Taiji-pipeline/Taiji-scATAC-seq", "max_stars_repo_head_hexsha": "6e912364ddce0f7ddcaae7938cd9696aac4937ca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Taiji/Pipeline/SC/ATACSeq/Functions/Feature/Peak.hs", "max_issues_repo_name": "Taiji-pipeline/Taiji-scATAC-seq", "max_issues_repo_head_hexsha": "6e912364ddce0f7ddcaae7938cd9696aac4937ca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Taiji/Pipeline/SC/ATACSeq/Functions/Feature/Peak.hs", "max_forks_repo_name": "Taiji-pipeline/Taiji-scATAC-seq", "max_forks_repo_head_hexsha": "6e912364ddce0f7ddcaae7938cd9696aac4937ca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2509960159, "max_line_length": 100, "alphanum_fraction": 0.5965199414, "num_tokens": 3190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630722, "lm_q2_score": 0.2877678157610531, "lm_q1q2_score": 0.17271489730542428}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes       #-}\n{-# LANGUAGE DataKinds                 #-}\n{-# LANGUAGE FlexibleContexts          #-}\n{-# LANGUAGE GADTs                     #-}\n{-# LANGUAGE NoMonomorphismRestriction #-}\n{-# LANGUAGE OverloadedStrings         #-}\n{-# LANGUAGE ScopedTypeVariables       #-}\n{-# LANGUAGE TypeApplications          #-}\n{-# LANGUAGE TypeOperators             #-}\n{-# LANGUAGE QuasiQuotes               #-}\n{-# LANGUAGE TypeFamilies              #-}\nmodule Main where\n\nimport qualified Control.Foldl                   as FL\nimport           Control.Monad.IO.Class           (MonadIO (..))\nimport qualified Data.List                       as List\n--import           Data.Maybe                       (fromMaybe)\nimport qualified Data.Map                        as M\nimport qualified Data.Profunctor                 as P\nimport qualified Data.Text                       as T\nimport qualified Data.Text.IO                    as T\nimport qualified Data.Text.Lazy                  as TL\nimport qualified Data.Vector.Storable            as V\nimport qualified Data.Vector                     as VB\nimport qualified Data.Vinyl                      as V\nimport qualified Frames                          as F\nimport qualified Frames.InCore                   as FI\n\nimport qualified Numeric.LinearAlgebra           as LA\nimport           Numeric.LinearAlgebra            (R\n                                                  , Matrix\n                                                  )\n\nimport qualified Text.Blaze.Html.Renderer.Text   as BH\n\nimport qualified Knit.Report                   as K\n\nimport qualified Frames.MapReduce as MR\nimport qualified Frames.Folds                    as FF\nimport qualified Frames.Transform                as FT\nimport           Frames.Table                    (blazeTable\n                                                 , RecordColonnade\n                                                 )\n\nimport           Data.String.Here\n\ntemplateVars = M.fromList\n  [\n    (\"lang\", \"English\")\n  , (\"author\", \"Adam Conner-Sax\")\n  , (\"pagetitle\", \"Map Reduce Examples\")\n--  , (\"tufte\",\"True\")\n  ]\n\n-- this is annoying.  Where should this instance live?\ntype instance FI.VectorFor (Maybe a) = VB.Vector\n\nmapReduceNotesMD\n  = [here|\n## Map Reduce Examples\n|]\n\nmain :: IO ()\nmain = asPandoc\n  \nasPandoc :: IO ()\nasPandoc = do\n  let pandocWriterConfig = K.PandocWriterConfig (Just \"pandoc-templates/minWithVega-pandoc.html\")  templateVars K.mindocOptionsF\n  htmlAsTextE <- K.knitHtml (Just \"MapReduce.Main\") K.logAll pandocWriterConfig $ do\n    let rows :: Int = 20000\n        vars = unweighted rows\n        yNoise = 1.0\n    K.logLE K.Info \"Creating data\"    \n    frame <- liftIO (noisyData vars yNoise coeffs >>= makeFrame vars)    \n    K.addMarkDown mapReduceNotesMD\n    testMapReduce frame (showText rows <> \" rows, average of X and Y by label.\") mrAvgXYByLabel\n    testMapReduce frame (showText rows <> \" rows, filtered label, max of X and Y by label.\") mrMaxXYByLabelABC\n  case htmlAsTextE of\n    Right htmlAsText -> T.writeFile \"examples/html/mapReduce.html\" $ TL.toStrict  $ htmlAsText\n    Left err -> putStrLn $ \"pandoc error: \" ++ show err\n\ntype Label = \"label\" F.:-> T.Text\ntype Y = \"y\" F.:-> Double\ntype X = \"x\" F.:-> Double\ntype ZM = \"zMaybe\" F.:-> (Maybe Double)\ntype Weight = \"weight\" F.:-> Double\ntype IsDup = \"is_duplicate\" F.:-> Bool\ntype AllCols = [Label,Y,X,Weight]\n\n\n-- let's make some map-reductions on Frames of AllCols\n\n-- First some unpackings\nnoUnpack = MR.noUnpack\nfilterLabel ls = MR.filterUnpack (\\r -> (F.rgetField @Label r) `List.elem` ls)\nfilterMinX minX = MR.filterUnpack ((>= minX) . F.rgetField @X)\neditLabel f r = F.rputField @Label (f (F.rgetField @Label r)) r -- this would be better with lenses!!\nunpackDup = MR.Unpack $ \\r -> [r, editLabel (<> \"2\") r]\n\n-- some assignings\nassignToLabels = MR.assignKeys @'[Label]\nassignDups = MR.assign @(F.Record '[IsDup]) (\\r -> (T.length (F.rgetField @Label r) > 1) F.&: V.RNil) (F.rcast @[Y,X,Weight])\n\n\n-- some reductions\n--averageF :: FL.Fold (F.FrameRec '[X,Y]) F.Record '[X,Y]\naverageF = FF.foldAllConstrained @RealFloat FL.mean\n\n--maxX :: FL.Fold (F.Record '[X]) (F.Record '[ZM])\nmaxX = P.dimap (F.rgetField @X) (FT.recordSingleton @ZM) FL.maximum\n\n--maxXY :: FL.Fold (F.Record '[X,Y]) (F.Record '[MX])\nmaxXY = P.dimap (\\r -> Prelude.max (F.rgetField @X r) (F.rgetField @Y r)) (FT.recordSingleton @ZM) FL.maximum\n\n-- put them together\n--mrAvgXYByLabel :: FL.Fold (F.Record AllCols) (F.FrameRec AllCols)\nmrAvgXYByLabel = MR.concatFold $ MR.mapReduceFold noUnpack (MR.splitOnKeys @'[Label]) (MR.foldAndAddKey averageF)\n\n--mrAvgXYByLabelP :: FL.Fold (F.Record AllCols) (F.FrameRec AllCols)\n--mrAvgXYByLabelP = MR.parBasicListHashableFold 1000 6 noUnpack (MR.splitOnKeys @'[Label]) (MR.foldAndAddKey averageF)\n--  MR.MR.mapReduceGF (MRP.defaultParReduceGatherer pure) \n\nmrMaxXYByLabelABC :: FL.Fold (F.Record AllCols) (F.FrameRec '[Label,ZM])\nmrMaxXYByLabelABC = MR.concatFold $ MR.mapReduceFold (filterLabel [\"A\",\"B\",\"C\"]) assignToLabels (MR.foldAndAddKey maxXY)\n\nnoisyData :: [Double] -> Double -> LA.Vector R -> IO (LA.Vector R, LA.Matrix R)\nnoisyData variances noiseObs coeffs = do\n  -- generate random measurements\n  let d = LA.size coeffs\n      nObs = List.length variances\n  let xs0 :: Matrix R = LA.asColumn $ LA.fromList $ [-0.5 + (realToFrac i/realToFrac nObs) | i <- [0..(nObs-1)]]\n  let xsC = 1 LA.||| xs0\n      ys0 = xsC LA.<> LA.asColumn coeffs\n  yNoise <- fmap (List.head . LA.toColumns) (LA.randn nObs 1) -- 0 centered normally (sigma=1) distributed random numbers\n  let ys = ys0 + LA.asColumn (LA.scale noiseObs (V.zipWith (*) yNoise (LA.cmap sqrt (LA.fromList variances))))\n  return (List.head (LA.toColumns ys), xsC)\n\nmakeFrame :: [Double] -> (LA.Vector R, LA.Matrix R) -> IO (F.FrameRec AllCols)\nmakeFrame vars (ys, xs) = do\n  if snd (LA.size xs) /= 2 then error (\"Matrix of xs wrong size (\" ++ show (LA.size xs) ++ \") for makeFrame\") else return ()\n  let rows = LA.size ys\n      rowIndex = [0..(rows - 1)]\n      makeLabel :: Int -> Char\n      makeLabel n = toEnum (fromEnum 'A' + n `mod` 26)\n      makeRecord :: Int -> F.Record AllCols\n      makeRecord n = T.pack [makeLabel n] F.&: ys `LA.atIndex` n F.&: xs `LA.atIndex` (n,1) F.&: vars List.!! n F.&: V.RNil -- skip bias column\n  return $ F.toFrame $ makeRecord <$> rowIndex\n\nunweighted :: Int -> [Double]\nunweighted n = List.replicate n (1.0)\n\ncoeffs :: LA.Vector R = LA.fromList [1.0, 2.2]\n\ntestMapReduce :: ( RecordColonnade as\n                 , K.Member K.ToPandoc effs\n                 , K.PandocEffects effs\n                 , MonadIO (K.Sem effs)\n                 , Show (F.Record as))\n              => F.FrameRec AllCols\n              -> T.Text \n              -> FL.Fold (F.Record AllCols) (F.FrameRec as)\n              -> K.Sem effs ()\ntestMapReduce dataFrame title mrFold = do\n  K.logLE K.Info $ \"Doing map-reduce fold: \" <> title    \n  let resFrame = FL.fold mrFold dataFrame\n      header _ _ = title\n  K.addMarkDown $ \"\\n## \" <> title \n  K.addBlaze $ blazeTable resFrame\n\n\n\nshowText :: Show a => a -> T.Text\nshowText = T.pack . show\n\n", "meta": {"hexsha": "b1aa7f89d2b85b9cf5bd66c8a37c8fa59b4a225d", "size": 7123, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "examples/MapReduce.hs", "max_stars_repo_name": "teto/Frames-utils", "max_stars_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-01-17T21:51:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T08:20:19.000Z", "max_issues_repo_path": "examples/MapReduce.hs", "max_issues_repo_name": "teto/Frames-utils", "max_issues_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-03-22T13:50:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T13:50:50.000Z", "max_forks_repo_path": "examples/MapReduce.hs", "max_forks_repo_name": "teto/Frames-utils", "max_forks_repo_head_hexsha": "10f5687f92d4e2004831d3153c8ae1dd20f48b18", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-04-04T12:49:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T11:25:11.000Z", "avg_line_length": 40.7028571429, "max_line_length": 143, "alphanum_fraction": 0.6083111049, "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.1686198076352008}}
{"text": "{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# OPTIONS_GHC -Wincomplete-patterns #-}\n\n--{-# OPTIONS_GHC -W #-}\n\nmodule Symphony.Symphony where\n\nimport AbsHashedLang\nimport Codec.Picture\nimport Control.Monad (when)\nimport Control.Monad.Except\nimport qualified Data.Array as Array\nimport Data.Char (toLower)\nimport Data.Complex\nimport Data.List (intercalate)\nimport Data.List.Extra (firstJust)\nimport Data.Map (Map)\nimport qualified Data.Map.Strict as Map\nimport Data.Maybe (fromMaybe, mapMaybe)\nimport qualified Data.Set as Set\nimport Data.Tuple.HT (fst3)\nimport ErrM\nimport HashedExpression.Codegen\nimport qualified HashedExpression.Codegen.CSimple as CSimple\nimport HashedExpression.Internal\nimport HashedExpression.Internal.Expression (ExpressionMap, NodeID, Op (..))\nimport qualified HashedExpression.Internal.Expression as HE\nimport qualified HashedExpression.Internal.Node as HN\nimport HashedExpression.Internal.Utils\nimport qualified HashedExpression.Operation as HO\nimport HashedExpression.Prettify\nimport qualified HashedExpression.Problem as HS\nimport qualified HashedExpression.Value as HV\nimport LayoutHashedLang\nimport LexHashedLang\nimport ParHashedLang\nimport Symphony.Common\nimport Symphony.Exp\nimport Symphony.Solver\nimport Text.Regex.Posix\n\nmyLLexer :: String -> [Token]\nmyLLexer = resolveLayout True . myLexer\n\n-------------------------------------------------------------------------------\n-- Parse content of symphony file\n-- Thanks to BNFC, we only need a simple call to `pProblem`\nparse :: String -> Result Problem\nparse fileContent =\n  case pProblem . myLLexer $ fileContent of\n    Ok problem -> return problem\n    Bad errStr ->\n      case (errStr =~ \"line ([0-9]+), column ([0-9]+)\" :: (String, String, String, [String])) of\n        (_, _, _, [rs, cs]) ->\n          -- because layout parsing add dummy ';'\n          let r = min (read rs) (length r2c)\n              c = min (read cs) (getNumColumn r)\n           in throwError $ SyntaxError (r, c)\n        _ -> throwError $ SyntaxError (1, 1)\n  where\n    r2c = Map.fromList . zip [1 ..] . map length . lines $ fileContent\n    getNumColumn r = fromMaybe 0 $ Map.lookup r r2c\n\ndata ValidSymphony = ValidSymphony (ExpressionMap, NodeID) Vars Consts [HS.ConstraintStatement] AvailableSolver\n\n-------------------------------------------------------------------------------\n-- 1. Check if there is variables block\n-- 2. Check if variable block is valid (no name clash)\n-- 3. If there is a constant, check if it is valid (no name clash)\n-- 4. Check if all expressions (in constraints and objective) is valid (should be scalar, all operation should be valid),\n--        if yes construct Expression.\n-- 5. Gen code\ncheckSemantic :: Problem -> Result ValidSymphony\ncheckSemantic problem = do\n  let toVar name (shape, _) = varWithShape shape name\n  let toParam name (shape, _) = paramWithShape shape name\n  varDecls <- getVarDecls problem -- 1\n  vars <- foldM checkVariableDecl Map.empty varDecls -- 2\n  constDecls <- getConstDecls problem\n  consts <- foldM (checkConstantDecl vars) Map.empty constDecls\n  let initContext =\n        Context\n          { declarations = Map.mapWithKey toVar vars `Map.union` Map.mapWithKey toParam consts,\n            vars = vars,\n            consts = consts\n          }\n  letDecls <- getLetDecls problem\n  finalContext <- foldM checkLetDecl initContext letDecls\n  -- Complete processing context (variables, constants, declared values)\n  -- Constraint\n  constraintDecls <- getConstraintDecls problem\n  css <- foldM (checkConstraintDecl finalContext) [] constraintDecls\n  -- Objective\n  parseObjectiveExp <- getMinimizeBlock problem\n  objectiveExp <- constructExp finalContext (Just []) parseObjectiveExp\n  -- Solver\n  let shape = getShape objectiveExp\n      nt = getNT objectiveExp\n  solver <- getSolver problem\n  when (shape /= [] || nt /= HE.R) $\n    throwError $\n      ErrorWithPosition\n        ( \"Objective should be a real scalar, here it is (\"\n            ++ toReadable shape\n            ++ \", \"\n            ++ show nt\n            ++ \")\"\n        )\n        (getBeginningPosition parseObjectiveExp)\n  liftIO $ putStrLn \"Syntax & semantic is correct\"\n  return $ ValidSymphony objectiveExp vars consts css solver\n\n-------------------------------------------------------------------------------\n\n-- | Generate code\ngenerateCode :: String -> ValidSymphony -> Result ()\ngenerateCode outputPath (ValidSymphony objectiveExp vars consts css solver) = do\n  let problemGen =\n        HS.constructProblem\n          -- Objective\n          (wrap objectiveExp)\n          -- Constraints\n          (HS.Constraint css)\n  heProblem <- liftEitherString problemGen\n--  case problemGen of\n--    HS.ProblemValid heProblem -> do\n  let valMap = Map.mapMaybeWithKey varVal vars `Map.union` Map.mapMaybeWithKey constVal consts\n  res <- liftEitherString $ generateProblemCode CSimple.CSimpleConfig {output = CSimple.OutputHDF5} heProblem valMap\n--  case generateProblemCode CSimple.CSimpleConfig {output = CSimple.OutputHDF5} heProblem valMap of\n--    Invalid reason -> throwError $ GeneralError reason\n--    Success res -> do\n  liftIO $ putStrLn \"Problem detail:\"\n  liftIO $ print $ heProblem\n  liftIO $ res outputPath\n  liftIO $ putStrLn \"Download solver & adapter......\"\n  liftIO $ downloadSolver outputPath solver\n--    HS.ProblemInvalid reason -> throwError $ GeneralError reason\n  where\n    varVal _ (_, Just val) = Just val\n    varVal _ _ = Nothing\n    constVal _ (_, val) = Just val\n\n-------------------------------------------------------------------------------\n\n-- | Get variable declarations, there must be exact 1 variables block\ngetVarDecls :: Problem -> Result [VariableDecl]\ngetVarDecls (Problem blocks) =\n  case filter isVariableBlock blocks of\n    [] -> throwError $ GeneralError \"No variale block\"\n    [BlockVariable declss] -> return $ concat declss\n    _ -> throwError $ GeneralError \"There are more than 1 variables block\"\n  where\n    isVariableBlock (BlockVariable declss) = True\n    isVariableBlock _ = False\n\n-------------------------------------------------------------------------------\n\n-- | Get constants declarations, there must be at most 1 constants block\ngetConstDecls :: Problem -> Result [ConstantDecl]\ngetConstDecls (Problem blocks) =\n  case filter isConstantBlock blocks of\n    [] -> return []\n    [BlockConstant declss] -> return $ concat declss\n    _ -> throwError $ GeneralError \"There are more than 1 constant block\"\n  where\n    isConstantBlock (BlockConstant declss) = True\n    isConstantBlock _ = False\n\n-------------------------------------------------------------------------------\n\n-- | Get constraints declarations, there must be at most 1 constraints block\ngetConstraintDecls :: Problem -> Result [ConstraintDecl]\ngetConstraintDecls (Problem blocks) =\n  case filter isConstraintBlock blocks of\n    [] -> return []\n    [BlockConstraint declss] -> return $ concat declss\n    _ -> throwError $ GeneralError \"There are more than 1 constraint block\"\n  where\n    isConstraintBlock (BlockConstraint declss) = True\n    isConstraintBlock _ = False\n\n-------------------------------------------------------------------------------\n\n-- | Get immediate declarations, at most 1 block\ngetLetDecls :: Problem -> Result [LetDecl]\ngetLetDecls (Problem blocks) =\n  case filter isLetBlock blocks of\n    [] -> return []\n    [BlockLet declss] -> return $ concat declss\n    _ -> throwError $ GeneralError \"There are more than 1 let block\"\n  where\n    isLetBlock (BlockLet declss) = True\n    isLetBlock _ = False\n\n-------------------------------------------------------------------------------\n\n-- | Get objective block, must be 1 block\ngetMinimizeBlock :: Problem -> Result Exp\ngetMinimizeBlock (Problem blocks) =\n  case filter isMinimizeBlock blocks of\n    [] -> throwError $ GeneralError \"No minimize block\"\n    [BlockMinimize exp] -> return exp\n    _ -> throwError $ GeneralError \"There are more than 1 minimize block\"\n  where\n    isMinimizeBlock (BlockMinimize declss) = True\n    isMinimizeBlock _ = False\n\n-- | Get the solver\ngetSolver :: Problem -> Result AvailableSolver\ngetSolver (Problem blocks) =\n  case filter isSolverBlock blocks of\n    [] -> do\n      lift $ putStrLn \"No solver specified, default to L-BFGS-B (https://github.com/stephenbeckr/L-BFGS-B-C)\"\n      return LBFGSB\n    [BlockSolver (SolverName name)]\n      | map toLower name `elem` [\"lbfgs-b\", \"lbfgsb\", \"l-bfgs-b\"] -> return LBFGSB\n      | map toLower name `elem` [\"ipopt\"] -> return Ipopt\n      | otherwise -> throwError $ GeneralError \"Unknown solver, should be (ipopt | lbfgs-b)\"\n    _ -> throwError $ GeneralError \"More than one solver specified\"\n  where\n    isSolverBlock (BlockSolver name) = True\n    isSolverBlock _ = False\n\n-------------------------------------------------------------------------------\n\n-- | Check variable declarations\ncheckVariableDecl :: Vars -> VariableDecl -> Result Vars\ncheckVariableDecl accRes decl = do\n  let checkName name pos =\n        when (name `Map.member` accRes) $\n          throwError $\n            ErrorWithPosition (\"Duplicate declaration of \" ++ name) pos\n  case decl of\n    VariableNoInit (PIdent (pos, name)) shape -> do\n      checkName name pos\n      return $ Map.insert name (toHEShape shape, Nothing) accRes\n    VariableWithInit (PIdent (pos, name)) shape val -> do\n      checkName name pos\n      checkVal (toHEShape shape) val\n      let heShape = toHEShape shape\n      heVal <- toHEVal heShape val\n      return $ Map.insert name (heShape, Just heVal) accRes\n\n-------------------------------------------------------------------------------\n\n-- | Check constant declarations\ncheckConstantDecl :: Vars -> Consts -> ConstantDecl -> Result Consts\ncheckConstantDecl vars accRes decl = do\n  let (ConstantDecl (PIdent (pos, name)) shape val) = decl\n  when (name `Map.member` accRes) $\n    throwError $\n      ErrorWithPosition (\"Duplicate declaration of \" ++ name) pos\n  when (name `Map.member` vars) $\n    throwError $\n      ErrorWithPosition (name ++ \" already defined as variables\") pos\n  let heShape = toHEShape shape\n  checkVal heShape val\n  heVal <- toHEVal heShape val\n  return $ Map.insert name (toHEShape shape, heVal) accRes\n\n-------------------------------------------------------------------------------\n\n-- | Check constraints declarations\ncheckConstraintDecl ::\n  Context ->\n  [HS.ConstraintStatement] ->\n  ConstraintDecl ->\n  Result [HS.ConstraintStatement]\ncheckConstraintDecl context@Context {..} acc decl = do\n  (constructedExp, boundVal) <-\n    case (isVariable exp, bound) of\n      (Just varExp, ConstantBound (PIdent (pos, name)))\n        | Just (shape, val) <- Map.lookup name consts -> do\n          when (shape /= getShape varExp) $\n            throwError $\n              ErrorWithPosition\n                \"Shape mismatched: the bound doesn't have same shape as the variable\"\n                pos\n          return (varExp, val)\n        | otherwise ->\n          throwError $ ErrorWithPosition (name ++ \" not found\") pos\n      (Just varExp, NumberBound num) ->\n        return (varExp, HV.VNum (numToDouble num))\n      _ -> do\n        scalarExp <- constructExp context Nothing exp\n        when (getShape scalarExp /= []) $\n          throwError $\n            ErrorWithPosition\n              ( \"Higher-dimension (in)equality is not supported yet, here the expression has shape \"\n                  ++ toReadable (getShape scalarExp)\n              )\n              (getBeginningPosition exp)\n        case bound of\n          ConstantBound (PIdent (pos, name))\n            | Just (shape, val) <- Map.lookup name consts -> do\n              when (shape /= getShape scalarExp) $\n                throwError $\n                  ErrorWithPosition \"The bound must be scalar\" pos\n              return (scalarExp, val)\n            | otherwise ->\n              throwError $\n                ErrorWithPosition (name ++ \" not found\") pos\n          NumberBound num ->\n            return (scalarExp, HV.VNum (numToDouble num))\n  let newEntry =\n        case decl of\n          ConstraintLower {} -> HS.Lower constructedExp boundVal\n          ConstraintUpper {} -> HS.Upper constructedExp boundVal\n          ConstraintEqual {} ->\n            HS.Between constructedExp (boundVal, boundVal)\n  return $ acc ++ [newEntry]\n  where\n    (exp, bound) =\n      case decl of\n        ConstraintLower exp bound -> (exp, bound)\n        ConstraintUpper exp bound -> (exp, bound)\n        ConstraintEqual exp bound -> (exp, bound)\n    isVariable exp =\n      case exp of\n        EIdent (PIdent (_, name))\n          | Just constructedExp <- Map.lookup name declarations,\n            name `Map.member` vars ->\n            Just constructedExp\n        _ -> Nothing\n\n-------------------------------------------------------------------------------\n\n-- | Check immediate declarations\ncheckLetDecl :: Context -> LetDecl -> Result Context\ncheckLetDecl context@Context {..} (LetDecl (PIdent (pos, name)) exp) = do\n  when (name `Map.member` consts) $\n    throwError $\n      ErrorWithPosition (name ++ \" already defined as a constant\") pos\n  when (name `Map.member` vars) $\n    throwError $\n      ErrorWithPosition (name ++ \" already defined as a variable\") pos\n  when (name `Map.member` declarations) $\n    throwError $\n      ErrorWithPosition (name ++ \" already taken\") pos\n  constructedExp <- constructExp context Nothing exp\n  let newDeclarations = Map.insert name constructedExp declarations\n  return $ context {declarations = newDeclarations}\n\n-------------------------------------------------------------------------------\n\n-- | To HashedExpression's value\ntoHEVal :: HE.Shape -> Val -> Result HV.Val\ntoHEVal shape v =\n  case v of\n    ValFile filePath -> return $ HV.VFile $ HV.TXT filePath\n    ValDataset filePath dataset ->\n      return $ HV.VFile $ HV.HDF5 filePath dataset\n    ValPattern (KWDataPattern pattern) ->\n      case (pattern, shape) of\n        (\"FIRST_ROW_1\", [size1, size2]) ->\n          return\n            . HV.V2D\n            . Array.listArray ((0, 0), (size1 - 1, size2 - 1))\n            $ replicate size2 1 ++ repeat 0\n        (\"LAST_ROW_1\", [size1, size2]) ->\n          return\n            . HV.V2D\n            . Array.listArray ((0, 0), (size1 - 1, size2 - 1))\n            $ replicate (size2 * (size1 - 1)) 0 ++ repeat 1\n        (\"FIRST_COLUMN_1\", [size1, size2]) ->\n          return\n            . HV.V2D\n            . Array.listArray ((0, 0), (size1 - 1, size2 - 1))\n            $ concat $\n              replicate size1 $\n                1 : replicate (size2 - 1) 0\n        (\"LAST_COLUMN_1\", [size1, size2]) ->\n          return\n            . HV.V2D\n            . Array.listArray ((0, 0), (size1 - 1, size2 - 1))\n            $ concat $\n              replicate size1 $\n                replicate (size2 - 1) 0 ++ [1]\n        (\"FIRST_ROW_0\", [size1, size2]) ->\n          return\n            . HV.V2D\n            . Array.listArray ((0, 0), (size1 - 1, size2 - 1))\n            $ replicate size2 0 ++ repeat 1\n        (\"LAST_ROW_0\", [size1, size2]) ->\n          return\n            . HV.V2D\n            . Array.listArray ((0, 0), (size1 - 1, size2 - 1))\n            $ replicate (size2 * (size1 - 1)) 1 ++ repeat 0\n        (\"FIRST_COLUMN_0\", [size1, size2]) ->\n          return\n            . HV.V2D\n            . Array.listArray ((0, 0), (size1 - 1, size2 - 1))\n            $ concat $\n              replicate size1 $\n                0 : replicate (size2 - 1) 1\n        (\"LAST_COLUMN_0\", [size1, size2]) ->\n          return\n            . HV.V2D\n            . Array.listArray ((0, 0), (size1 - 1, size2 - 1))\n            $ concat $\n              replicate size1 $\n                replicate (size2 - 1) 1 ++ [0]\n        _ ->\n          throwError $\n            GeneralError $\n              \"Pattern \"\n                ++ pattern\n                ++ \" is incompatible with the shape or not supported yet\"\n    ValRandom -> return $ HV.VNum 3\n    ValLiteral num -> return $ HV.VNum (numToDouble num)\n    ValImage imgPath -> do\n      a <- liftIO $ readImage imgPath\n      case a of\n        Left err -> throwError $ GeneralError $ \"Error reading image at \" <> imgPath <> \":\" <> err\n        Right v -> do\n          -- TODO : only support grayscale yet, and this is very slow\n          let img = convertRGB8 v\n          let col = imageWidth img\n              row = imageHeight img\n              toGrayscale :: Pixel8 -> Pixel8 -> Pixel8 -> Double\n              toGrayscale r g b = (0.2126 * (fromIntegral r) + 0.7152 * (fromIntegral g) + 0.0722 * (fromIntegral b)) / 256\n          if (shape /= [row, col])\n            then throwError $ GeneralError $ \"image size and variable shape don't match, image size is \" ++ show row ++ \"x\" ++ show col\n            else\n              return $\n                HV.V2D $\n                  Array.listArray\n                    ((0, 0), (row - 1, col - 1))\n                    [ toGrayscale r g b\n                      | i <- [0 .. row - 1],\n                        j <- [0 .. col - 1],\n                        let (PixelRGB8 r g b) = pixelAt img j i\n                    ]\n", "meta": {"hexsha": "c62b8cb112e77275b04c9342d3336210888e07ad", "size": 17045, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Symphony/Symphony.hs", "max_stars_repo_name": "McMasterU/Symphony", "max_stars_repo_head_hexsha": "90a8cc1f10084b7d41e87de944c31949ac726008", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Symphony/Symphony.hs", "max_issues_repo_name": "McMasterU/Symphony", "max_issues_repo_head_hexsha": "90a8cc1f10084b7d41e87de944c31949ac726008", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Symphony/Symphony.hs", "max_forks_repo_name": "McMasterU/Symphony", "max_forks_repo_head_hexsha": "90a8cc1f10084b7d41e87de944c31949ac726008", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0940366972, "max_line_length": 135, "alphanum_fraction": 0.596949252, "num_tokens": 4068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.31742626558767584, "lm_q1q2_score": 0.16738411479905235}}
{"text": "\n{-# OPTIONS_GHC -Wall #-}\n\n{-|\n\n  Module      : AutoBench.Internal.Types\n  Description : Datatypes and associated helper functions\\/defaults.\n  Copyright   : (c) 2018 Martin Handley\n  License     : BSD-style\n  Maintainer  : martin.handley@nottingham.ac.uk\n  Stability   : Experimental\n  Portability : GHC\n\n  Datatypes used internally throughout AutoBench's implementation and any \n  associated helper functions\\/defaults.\n\n-}\n\n{-\n   ----------------------------------------------------------------------------\n   <TO-DO>:\n   ----------------------------------------------------------------------------\n   - 'DataOpts' Discover setting;\n   - Make AnalOpts in TestSuite a maybe type? In case users don't want to \n     analyse right away;\n   - 'UserInputs' PP doesn't wrap;\n   - 'TestSuite's PP isn't alphabetical by test program name;\n-}\n\nmodule AutoBench.Internal.Types \n  (\n\n  -- * Re-exports\n    module AutoBench.Types\n  -- * User inputs\n  -- ** Test data options\n  , toHRange               -- Convert @Gen l s u :: DataOpts@ to a Haskell range.\n  -- ** Internal representation of user inputs\n  , UserInputs(..)         -- A data structure maintained by the system to classify user inputs.\n  , initUserInputs         -- Initialise a 'UserInputs' data structure.\n  -- * Benchmarking\n  , BenchReport(..)        -- A report to summarise the benchmarking phase of testing.\n  , Coord                  -- (Input Size, Runtime) results as coordinates for unary test programs.\n  , Coord3                 -- (Input Size, Input Size, Runtime) results as coordinates for binary test programs.\n  , DataSize(..)           -- The size of unary and binary test data.\n  , SimpleReport(..)       -- A simplified version of Criterion's 'Report'. See 'Criterion.Types.Report'.\n  -- * Test results \n  , TestReport(..)         -- A report to summarise the system's testing phase.\n  -- ** QuickBench\n  , QuickReport(..)        -- A report to summarise the QuickBench phase of testing.\n  -- * Statistical analysis \n  , AnalysisReport(..)     -- A report to summarise the system's analysis phase.                                                                                 \n  , CVStats(..)            -- Fitting statistics calculated for regression models per each iteration of cross-validation.\n  , Improvement            -- An efficiency improvement is an ordering between two test programs and a rating\n                           -- 0 <= d <= 1 that corresponds to the percentage of test cases that support the ordering.\n  , Exp                    -- Expressions with 'Double' literals.\n  , LinearCandidate(..)    -- The details of a regression model necessary to fit it to a given dataset.\n  , LinearFit(..)          -- A regression model's fitting statistics and helper functions: predicting y-coordinates, pretty printing.\n  , SimpleResults(..)      -- Simple statistical analysis results for each test program.\n  , numPredictors          -- Number of predictors for each type of model.\n  , simpleReportToCoord    -- Convert a 'SimpleReport' to a (input size(s), runtime) coordinate, i.e., 'Coord' or 'Coord3'.\n  , simpleReportsToCoords  -- Convert a list of 'SimpleReport' to a (input size(s), runtime) coordinate, i.e., 'Coord' or 'Coord3'.\n  -- ** QuickBench\n  , QuickAnalysis(..)      -- A report to summarise the system's analysis phase for QuickBenching.\n  , QuickResults(..)       -- Simple statistical analysis results for each test program for QuickBenching.\n  -- * Errors\n  -- ** System errors\n  , SystemError(..)        -- System errors.\n  -- ** Input errors\n  , InputError(..)         -- User input errors.\n\n  ) where\n\nimport           Control.Exception.Base (Exception)\nimport           Criterion.Types        (OutlierEffect(..))\nimport           Data.Either            (partitionEithers)\nimport           Numeric.LinearAlgebra  (Vector)\n\nimport qualified AutoBench.Internal.Expr as E\nimport           AutoBench.Types  -- Re-export.\n\nimport AutoBench.Internal.AbstractSyntax \n  ( HsType\n  , Id\n  , ModuleElem(..)\n  , TypeString\n  )\n\n-- * User inputs\n\n-- ** Test suites\n\n-- | Convert @Gen l s u :: DataOpts@ to a Haskell range.\ntoHRange :: DataOpts -> [Int]\ntoHRange Manual{}    = []\ntoHRange (Gen l s u) = [l, (l + s) .. u]\n\n-- ** Internal representation of user inputs\n\n-- | While user inputs are being analysed by the system, a 'UserInputs' data\n-- structure is maintained. The purpose of this data structure is to classify \n-- user inputs according to the properties they satisfy. For example, when the \n-- system first interprets a user input file, all of its definitions are added \n-- to the '_allElems' list. This list is then processed to determine which \n-- definitions have function types that are syntactically compatible with the \n-- requirements of the system (see 'AutoBench.Internal.StaticChecks'). \n-- Definitions that are compatible are added to the '_validElems' list, and \n-- those that aren't are added to the '_invalidElems' list. Elements in the \n-- '_validElems' list are then classified according to, for example, whether \n-- they are nullary, unary, or binary functions. This check process continues\n-- until all user  inputs are classified according to the list headers below. \n-- Note that both static ('AutoBench.Internal.StaticChecks') and dynamic \n-- ('AutoBench.Internal.DynamicChecks') checks are required to classify user \n-- inputs.\n--\n-- Notice that each /invalid/ definitions has one or more input errors \n-- associated with it.\n--\n-- After the system has processed all user inputs, users can review this data \n-- structure to see how the system has classified their inputs, and if any \n-- input errors have been generated. \ndata UserInputs = \n  UserInputs\n   {\n     _allElems           :: [(ModuleElem, Maybe TypeString)]         -- ^ All definitions in a user input file.\n   , _invalidElems       :: [(ModuleElem, Maybe TypeString)]         -- ^ Syntactically invalid definitions (see 'AutoBench.Internal.AbstractSyntax').\n   , _validElems         :: [(Id, HsType)]                           -- ^ Syntactically valid definitions (see 'AutoBench.Internal.AbstractSyntax').\n   , _nullaryFuns        :: [(Id, HsType)]                           -- ^ Nullary functions.\n   , _unaryFuns          :: [(Id, HsType)]                           -- ^ Unary functions.\n   , _binaryFuns         :: [(Id, HsType)]                           -- ^ Binary functions.\n   , _arbFuns            :: [(Id, HsType)]                           -- ^ Unary/binary functions whose input types are members of the Arbitrary type class.\n   , _benchFuns          :: [(Id, HsType)]                           -- ^ Unary/binary functions whose input types are members of the NFData type class.\n   , _nfFuns             :: [(Id, HsType)]                           -- ^ Unary/binary functions whose result types are members of the NFData type class.\n   , _invalidData        :: [(Id, HsType, [InputError])]             -- ^ Invalid user-specified test data. \n   , _unaryData          :: [(Id, HsType, [Int])]                    -- ^ Valid user-specified test data for unary functions /with size information/.\n   , _binaryData         :: [(Id, HsType, [(Int, Int)])]             -- ^ Valid user-specified test data for binary functions /with size information/.\n   , _invalidTestSuites  :: [(Id, [InputError])]                     -- ^ Invalid test suites.\n   , _testSuites         :: [(Id, TestSuite)]                        -- ^ Valid test suites.\n   }\n\n-- | Initialise a 'UserInputs' data structure by specifying the '_allElems' \n-- list. \ninitUserInputs :: [(ModuleElem, Maybe TypeString)] -> UserInputs\ninitUserInputs xs = \n  UserInputs\n    {\n      _allElems          = xs\n    , _invalidElems      = []\n    , _validElems        = []\n    , _nullaryFuns       = []\n    , _unaryFuns         = []\n    , _binaryFuns        = []\n    , _arbFuns           = []\n    , _benchFuns         = []\n    , _nfFuns            = []\n    , _invalidData       = []\n    , _unaryData         = []\n    , _binaryData        = []\n    , _invalidTestSuites = []\n    , _testSuites        = []\n    }\n\n-- * Benchmarking\n\n-- | (Input Size, Runtime) results as coordinates for unary test programs.\ntype Coord = (Double, Double)\n\n-- | (Input Size, Input Size, Runtime) results as coordinates for binary test \n-- programs.        \ntype Coord3 = (Double, Double, Double) \n\n-- | The size of unary and binary test data.\ndata DataSize = \n    SizeUn Int       -- ^ The size of unary test data.\n  | SizeBin Int Int  -- ^ The size of binary test data.\n    deriving (Ord, Eq)\n\n-- | A report to summarise the benchmarking phase of testing.\ndata BenchReport =\n  BenchReport \n    {\n      _reports   :: [[SimpleReport]]  -- ^ Individual reports for each test case, per test program.\n    , _baselines :: [SimpleReport]    -- ^ Baseline measurements (will be empty if '_baseline' is set to @False@).\n    }\n\n-- | A simplified version of Criterion's 'Report' datatype, see \n-- 'Criterion.Types.Report'.\ndata SimpleReport = \n  SimpleReport \n   { \n     _name       :: Id              -- ^ Name of test program.\n   , _size       :: DataSize        -- ^ Size of test data.\n   , _samples    :: Int             -- ^ Number of samples used to calculate statistics below.\n   , _runtime    :: Double          -- ^ Estimate runtime.\n   , _stdDev     :: Double          -- ^ Estimate standard deviation.\n   , _outVarEff  :: OutlierEffect   -- ^ Outlier effect. \n   , _outVarFrac :: Double          -- ^ Outlier effect as a percentage.\n   }\n\n-- * Test results \n\n-- | A report to summarise the system's testing phase.\ndata TestReport = \n  TestReport \n    {\n      _tProgs    :: [String]          -- ^ Names of all test programs.\n    , _tDataOpts :: DataOpts          -- ^ Which test data options were used.\n    , _tNf       :: Bool              -- ^ Whether test cases were evaluated to normal form.\n    , _tGhcFlags :: [String]          -- ^ Flags used when compiling the benchmarking file.\n    , _eql       :: Bool              -- ^ Whether test programs are semantically equal according to QuickCheck testing.\n    , _br        :: BenchReport       -- ^ Benchmarking report.\n    }\n\n-- ** QuickBench \n\n-- | A report to summarise the QuickBench testing phase.\ndata QuickReport = \n  QuickReport \n    {\n      _qName     :: Id                        -- ^ Name of test program.\n    , _qRuntimes :: Either [Coord] [Coord3]   -- ^ [(Input size(s), mean runtime)].\n    } deriving Show\n\n-- * Statistical analysis\n\n-- | A report to summarise the system's analysis phase.\ndata AnalysisReport = \n  AnalysisReport\n    {\n      _anlys :: [SimpleResults]       -- ^ Simple statistical analysis results per test program.   \n    , _imps  :: [Improvement]         -- ^ Improvement results.\n    , _blAn  :: Maybe SimpleResults   -- ^ Analysis of baseline measurements, if applicable.\n    }\n\n-- | Simple statistical analysis results for each test program. \ndata SimpleResults = \n  SimpleResults \n   {\n     _srIdt           :: Id                           -- ^ Name of test program.\n   , _srRaws          :: Either [Coord] [Coord3]      -- ^ Raw input size/runtime results.\n   , _srStdDev        :: Double                       -- ^ Standard deviation of all runtime results.\n   , _srAvgOutVarEff  :: OutlierEffect                -- ^ Average outlier effect. \n   , _srAvgPutVarFrac :: Double                       -- ^ Average outlier effect as a percentage.\n   , _srFits          :: [LinearFit]                  -- ^ Fitting statistics for each candidate model.\n   }\n\n-- | An efficiency improvement is an ordering between two test programs and a \n-- rating 0 <= d <= 1 that corresponds to the percentage of test cases that\n-- support the ordering.\ntype Improvement = (Id, Ordering, Id, Double)\n\n-- | Fitting statistics calculated for regression models per each iteration of\n-- cross-validation. Cumulative fitting statistics are produced by combining \n-- 'CVStats' from all iterations, for example, PMSE and PMAE. See 'Stats'. \ndata CVStats = \n  CVStats \n   { \n     _cv_mse    :: Double   -- ^ Mean squared error.\n   , _cv_mae    :: Double   -- ^ Mean absolute error.\n   , _cv_ss_tot :: Double   -- ^ Total sum of squares.\n   , _cv_ss_res :: Double   -- ^ Residual sum of squares.\n   } deriving Eq\n\n-- | Expressions with 'Double' literals.\ntype Exp = E.Expr Double\n\n-- | Each 'LinearType' gives rise to a 'LinearCandidate' that is then fitted to \n-- a given data set generating a 'LinearFit'. Unlike a 'LinearType', which\n-- just describes a particular regression model, a 'LinearCandidate' \n-- encompasses the required information to fit a model to a given data set. \n-- For example, it includes '_fxs' to transforms the raw x-coordinates \n-- of the dataset before fitting the model, and '_fyhat' which can be used to \n-- generate y-coordinates predicted by the model once it has been fit.\n--\n-- For example, if fitting a 'Log b 1' model, '_fxs' will transform each \n-- x-coordinate in the data set to log_b(x) before fitting. Then the linear \n-- relationship between the /resulting/ xy-coordinates corresponds to a \n-- logarithmic relationship between the /initial/ xy-coordinates.\n--\n-- When the coefficients of a model are determined by regression analysis, \n-- the corresponding 'LinearCandidate' gives rise to a 'LinearFit'.\ndata LinearCandidate = \n  LinearCandidate \n   { \n     _lct    :: LinearType                                         -- ^ The model.\n   , _fxs    :: Vector Double -> Vector Double                     -- ^ A function to transform x-coords before fitting.\n   , _fex    :: Vector Double -> Exp                               -- ^ A function to generate the model's equation as an 'Exp'.\n   , _fyhat  :: Vector Double -> Vector Double -> Vector Double    -- ^ A function to generate model's predicted y-coords.\n   }\n\n-- | When a 'LinearCandidate' is fitted to a given data set and its coefficients\n-- determined by regression analysis, a 'LinearFit' is generated. \n-- A 'LinearFit' primarily includes the fitting statistics ('Stats') of the \n-- model to be used to compare it against other models also fitted to the same \n-- data set. In order to be able to plot a 'LinearFit' on a results graph \n-- as a line of best fit, the '_yhat' function generates y-coordinates \n-- predicted by the model for a given set of x-coordinates. To pretty print the \n-- 'LinearFit', the '_ex' function generates an 'Exp' expression for the model's\n-- equation that has a pretty printing function.\ndata LinearFit =\n  LinearFit \n   { \n     _lft  :: LinearType                       -- ^ The model.\n   , _cfs  :: Vector Double                    -- ^ The coefficients of the model.\n   , _ex   :: Exp                              -- ^ The model's equation as an 'Exp'.\n   , _yhat :: Vector Double -> Vector Double   -- ^ A function to generate the model's predicted y-coords for a given set of x-coords.\n   , _sts  :: Stats                            -- ^ Fitting statistics.\n   }\n\n-- | Number of predictors for each type of model.\nnumPredictors :: LinearType -> Int \nnumPredictors (Poly      k) = k + 1 \nnumPredictors (Log     _ k) = k + 1 \nnumPredictors (PolyLog _ k) = k + 1 \nnumPredictors Exp{}         = 2\n\n-- | Convert a list of 'SimpleReport's to a list of (input size(s), runtime) \n-- coordinates, i.e., a list 'Coord's or 'Coord3's. The name of each \n-- simple report is verified against the given test program identifier.\nsimpleReportsToCoords :: Id -> [SimpleReport] -> Either [Coord] [Coord3]\nsimpleReportsToCoords idt srs = case (cs, cs3) of \n  ([], _) -> Right cs3 \n  (_, []) -> Left cs \n  _       -> Left [] -- Shouldn't happen.\n  where \n    srs' = filter (\\sr -> _name sr == idt) srs\n    (cs, cs3) = partitionEithers (fmap simpleReportToCoord srs')\n\n-- | Convert a 'SimpleReport' to a (input size(s), runtime) coordinate, \n-- i.e., 'Coord' or 'Coord3'.\nsimpleReportToCoord :: SimpleReport -> Either Coord Coord3 \nsimpleReportToCoord sr = case _size sr of \n  SizeUn n      -> Left  (fromIntegral n, _runtime sr)\n  SizeBin n1 n2 -> Right (fromIntegral n1, fromIntegral n2, _runtime sr)\n\n-- ** QuickBench \n\n-- | A report to summarise the system's analysis phase for QuickBenching.\ndata QuickAnalysis = \n  QuickAnalysis\n    {\n      _qAnlys :: [QuickResults]    -- ^ Quick results per test program.   \n    , _qImps  :: [Improvement]     -- ^ Improvement results.\n    }\n\n-- | Simple statistical analysis results for each test program for QuickBenching.\ndata QuickResults = \n  QuickResults \n   {\n     _qrIdt   :: Id                           -- ^ Name of test program.\n   , _qrRaws  :: Either [Coord] [Coord3]      -- ^ Raw input size/runtime results.\n   , _qrFits  :: [LinearFit]                  -- ^ Fitting statistics for each candidate model.\n   }\n\n-- * Errors \n\n-- | Errors raised by the system due to implementation failures. These can be \n-- generated at any time but are usually used to report unexpected IO results. \n-- For example, when dynamically checking user inputs (see \n-- 'AutoBench.Internal.UserInputChecks'), system errors are used to relay \n-- 'InterpreterError's thrown by functions in the hint package in cases\n-- where the system didn't expect errors to result.\ndata SystemError = InternalErr String\n\n-- Note: needed for the 'Exception' instance.\ninstance Show SystemError where \n  show (InternalErr s) = \"Internal error: \" ++ s ++ \"\\n** Please report on GitHub **\"\n\ninstance Exception SystemError\n\n-- ** Input errors\n\n-- | Input errors are generated by the system while analysing user input \n-- files. Examples input errors include erroneous test options, invalid test \n-- data, and test programs with missing Arbitrary/NFData instances.\n--\n-- In general, the system always attempts to continue with its execution for as \n-- long as possible. Therefore, unless a critical error is encountered, such as \n-- a filepath or file access error, it will collate all non-critical input \n-- errors. These will then be summarised after the user input file has been \n-- fully analysed.\ndata InputError = \n    FilePathErr   String    -- ^ Invalid filepath.\n  | FileErr       String    -- ^ File access error.\n  | TestSuiteErr  String    -- ^ Invalid test suite.\n  | DataOptsErr   String    -- ^ Invalid data options.\n  | AnalOptsErr   String    -- ^ Invalid statistical analysis options.\n  | TypeErr       String    -- ^ Invalid type signature.\n  | InstanceErr   String    -- ^ One or more missing instances\n  | TestReportErr String    -- ^ Invalid test report.\n  | QuickOptsErr  String    -- ^ Invalid quick options. See AutoBench.QuickBench.\n  | QuickBenchErr String    -- ^ QuickBench error. See AutoBench.QuickBench.\n\n-- Note: needed for the 'Exception' instance.\ninstance Show InputError where \n  show (FilePathErr   s) = \"File path error: \"        ++ s\n  show (FileErr       s) = \"File error: \"             ++ s\n  show (TestSuiteErr  s) = \"Test suite error: \"       ++ s\n  show (DataOptsErr   s) = \"Test data error: \"        ++ s\n  show (AnalOptsErr   s) = \"Analysis options error: \" ++ s\n  show (TypeErr       s) = \"Type error: \"             ++ s\n  show (InstanceErr   s) = \"Instance error: \"         ++ s\n  show (TestReportErr s) = \"Test report error: \"      ++ s\n  show (QuickOptsErr  s) = \"Quick options error: \"    ++ s\n  show (QuickBenchErr s) = \"QuickBench test error: \"  ++ s\n\ninstance Exception InputError", "meta": {"hexsha": "cf6ddea55e9d5c7cb61ff92a698f2e5b159bbc12", "size": 19262, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/AutoBench/Internal/Types.hs", "max_stars_repo_name": "recursion-ninja/AutoBench", "max_stars_repo_head_hexsha": "15b7da6fb39e01a5dd542e91fe4d9859f03acc0f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-18T15:14:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-18T15:14:24.000Z", "max_issues_repo_path": "src/AutoBench/Internal/Types.hs", "max_issues_repo_name": "recursion-ninja/AutoBench", "max_issues_repo_head_hexsha": "15b7da6fb39e01a5dd542e91fe4d9859f03acc0f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/AutoBench/Internal/Types.hs", "max_forks_repo_name": "recursion-ninja/AutoBench", "max_forks_repo_head_hexsha": "15b7da6fb39e01a5dd542e91fe4d9859f03acc0f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3267813268, "max_line_length": 161, "alphanum_fraction": 0.6281798359, "num_tokens": 4630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.33111975283019596, "lm_q1q2_score": 0.16685328663519972}}
{"text": "{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE LambdaCase #-}\n{-# LANGUAGE GADTs #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE TypeApplications #-}\n\nmodule Sketch where\n\nimport Foreign.C.Types\nimport Codec.Picture.ColorQuant\nimport Codec.Picture.Gif\nimport Numeric.LinearAlgebra.HMatrix as H hiding (reshape)\nimport Codec.Picture.Types\nimport Data.Int\nimport Foreign\nimport System.Environment\nimport Data.Time\nimport qualified SDL\nimport Prelude hiding (init)\nimport Graphics.Rendering.OpenGL as GL\nimport SDL.Vect\nimport Control.Monad.State as S hiding (get)\nimport Control.Lens\nimport qualified Data.Vector.Storable as SV\nimport Data.Map.Strict as M\n\nimport GLCode\nimport SDLCode\n\ndata World = World {\n        _windowSize :: (Int32, Int32),\n        _shaderProgram :: M.Map String GL.Program,\n        _mainWindow :: SDL.Window,\n        _startTime :: UTCTime\n    }\n\n$(makeLenses ''World)\n\nnewtype Options = Options {\n        _shaderDirectory :: FilePath\n    } deriving Show\n\n$(makeLenses ''Options)\n\ntype SketchMonad a = StateT World IO a\n\nlookupProgram :: String -> SketchMonad Program\nlookupProgram name = do\n    programs <- use shaderProgram\n    let Just program = M.lookup name programs\n    return program\n\nlookupEsp :: Either String Program -> SketchMonad Program\nlookupEsp (Left name) = lookupProgram name\nlookupEsp (Right program) = return program\n\n-- Uniforms\n\nclass UniformType a where\n    setUniform' :: Either String Program ->\n                  (Either String Program -> SketchMonad ()) -> a\n\ninstance (a ~ ()) => UniformType (SketchMonad a) where\n    setUniform' program cont = cont program\n\nsetUniform :: UniformType a => String -> a\nsetUniform name = setUniform' (Left name) $ \\_ -> return ()\n\n-- Uniform Float\ninstance (UniformType r) => UniformType (String -> Float -> r) where\n    setUniform' esp0 cont attr value = setUniform' esp0 $ \\esp1 -> do\n        program <- lookupEsp esp1\n        currentProgram $= Just program\n        loc <- get $ uniformLocation program attr\n        uniform loc GL.$= value\n        cont esp1\n\n-- Uniform vec2f\ninstance (UniformType r) => UniformType (String -> GL.Vertex2 Float -> r) where\n    setUniform' esp0 cont attr value = setUniform' esp0 $ \\esp1 -> do\n        program <- lookupEsp esp1\n        currentProgram $= Just program\n        loc <- get $ uniformLocation program attr\n        uniform loc GL.$= value\n        cont esp1\n\n-- Uniform mat4f\ninstance (UniformType r) => UniformType (String -> GL.GLmatrix Float -> r) where\n    setUniform' esp0 cont attr value = setUniform' esp0 $ \\esp1 -> do\n        program <- lookupEsp esp1\n        currentProgram $= Just program\n        loc <- get $ uniformLocation program attr\n        uniform loc GL.$= value\n        cont esp1\n\n-- Uniform mat4f\ninstance (UniformType r) => UniformType (String -> H.Matrix Float -> r) where\n    setUniform' esp0 cont attr value = setUniform' esp0 $ \\esp1 -> do\n        program <- lookupEsp esp1\n        currentProgram $= Just program\n        loc <- get $ uniformLocation program attr\n        matr <- io $ GL.newMatrix @GL.GLmatrix @Float GL.ColumnMajor $ concat $ H.toLists $ value\n        uniform loc GL.$= matr\n        cont esp1\n\n-- Some duplication here XXX\ninit :: FilePath -> CInt -> CInt -> CInt -> IO World\ninit path width height samples = do\n    window <- initWindow width height samples\n\n    start <- getCurrentTime\n    let world = World {\n        _windowSize = (fromIntegral width, fromIntegral height),\n        _shaderProgram = M.empty,\n        _mainWindow = window,\n        _startTime = start\n    }\n    programs <- installShaders path\n    return $ world & shaderProgram .~ M.fromList programs\n\nwithProgram :: String -> (GL.Program -> StateT World IO ()) -> StateT World IO ()\nwithProgram name cmd = do\n    programs <- use shaderProgram\n    forM_ (M.lookup name programs) cmd\n\n-- Going to be user responsibility to set window size\nreshape :: (Int32, Int32) -> StateT World IO ()\nreshape (w, h) = do\n    -- withProgram \"shader\" $ \\program -> io $ setShaderWindow program (w, h)\n    GL.viewport GL.$= (GL.Position 0 0, GL.Size (i w) (i h))\n    windowSize .= (w, h)\n\n-- Going to be user resposibility to set mouse\nmouse :: (Int32, Int32) -> StateT World IO ()\nmouse _ = return ()\n\n-- mouse (x, y) = withProgram $ \\program -> do\n--     (_, h) <- use windowSize\n--     io $ setShaderMouse program (x, h-y)\n\nhandleKey :: SDL.Keysym -> StateT World IO Bool\nhandleKey SDL.Keysym {SDL.keysymScancode = SDL.ScancodeEscape} = return True\nhandleKey SDL.Keysym { } = return False\n\nhandlePayload :: SDL.EventPayload -> StateT World IO Bool\nhandlePayload (SDL.WindowResizedEvent\n                            SDL.WindowResizedEventData { SDL.windowResizedEventSize = V2 w h }) =\n                            reshape (w, h) >> return False\nhandlePayload (SDL.MouseMotionEvent\n                            SDL.MouseMotionEventData { SDL.mouseMotionEventPos = P (V2 x y) }) =\n        mouse (x, y) >> return False\nhandlePayload (SDL.KeyboardEvent\n                            SDL.KeyboardEventData { SDL.keyboardEventKeyMotion = SDL.Pressed, SDL.keyboardEventKeysym = k }) =\n        handleKey k\nhandlePayload SDL.QuitEvent = return True\nhandlePayload _ = return False\n\nhandleUIEvent :: SDL.Event -> StateT World IO Bool\nhandleUIEvent SDL.Event { SDL.eventPayload = payload} = handlePayload payload\n\nparse :: Options -> [String] -> Options\nparse options [] = options\nparse options (\"-d\" : path : args) = parse (options { _shaderDirectory = path }) args\nparse _ args = error (\"Incomprehensible options \" ++ unwords args)\n\n{-\nmainLoop :: (Float -> StateT World IO ()) -> IO ()\nmainLoop render = do\n    args <- getArgs\n    let options = parse (Options { _shaderDirectory = \".\" }) args\n    print options\n     \n    SDL.initialize [SDL.InitVideo]\n\n    world <- init (_shaderDirectory options)\n\n    evalStateT (loop options render) world\n\nloop :: Options -> (Float -> StateT World IO ()) -> StateT World IO ()\nloop options render = do\n    window <- use mainWindow\n    interval <- realToFrac <$> (diffUTCTime <$> io getCurrentTime <*> use startTime)\n    -- user going to set time in shader\n    -- withProgram $ \\program -> io $ setShaderTime program interval\n    render interval\n    io $ SDL.glSwapWindow window\n    events <- io SDL.pollEvents\n    quit <- mapM handleUIEvent events\n    unless (or quit) $ loop options render\n-}\n\nmakeGif :: Int32 -> Int32 -> ForeignPtr (PixelBaseComponent PixelRGB8) -> Image PixelRGB8 \nmakeGif width32 height32 pixelData =\n    let width = fromIntegral width32\n        height = fromIntegral height32\n        array = SV.unsafeFromForeignPtr0 pixelData (width*height*3) :: SV.Vector (PixelBaseComponent PixelRGB8)\n    in Image width height array\n\ngifLoop :: String -> Float -> Int -> Int -> Options -> [(Palette, GifDelay, Image Pixel8)] -> (Float -> SketchMonad ()) -> SketchMonad ()\ngifLoop filename _ j n _ frames _ | j >= n = do\n    let Right zzz = writeGifImages filename LoopingForever frames \n    io zzz\ngifLoop filename fps j n options frames render = do\n    window <- use mainWindow\n    let interval = fromIntegral j\n    render (interval/fps)\n    (width, height) <- use windowSize\n    pixelData <- io (mallocForeignPtrArray (fromIntegral $ width*height*3) :: IO (ForeignPtr (PixelBaseComponent PixelRGB8)))\n    (im, pa) <- io $ withForeignPtr pixelData $ \\ptr -> do\n                GL.readPixels (GL.Position 0 0) (GL.Size width height) $ GL.PixelData GL.RGB GL.UnsignedByte ptr\n                let gif = makeGif width height pixelData\n                let (im, pa) = palettize defaultPaletteOptions gif\n                return (im, pa)\n    io $ SDL.glSwapWindow window\n    events <- io SDL.pollEvents\n    quit <- mapM handleUIEvent events\n    unless (or quit) $ gifLoop filename fps (j+1) n options ((pa, 4, im) : frames) render\n\ninitSketch :: IO Options\ninitSketch = do\n    SDL.initialize [SDL.InitVideo]\n    parse Options { _shaderDirectory = \".\" } <$> getArgs\n\nmainGifLoop :: String -> Float -> CInt -> CInt -> CInt -> Int -> Int -> (Float -> SketchMonad ()) -> IO ()\nmainGifLoop filename fps width height samples start end render = do\n    options <- initSketch\n    world <- init (_shaderDirectory options) width height samples\n    io $ evalStateT (gifLoop filename fps start end options [] render) world\n\nmainGifLoopState :: String -> Float -> CInt -> CInt -> CInt -> Int -> Int -> a -> (Float -> StateT a (StateT World IO) ()) -> IO ()\nmainGifLoopState filename fps width height samples start end initial render = do\n    options <- initSketch\n    world <- init (_shaderDirectory options) width height samples\n    evalStateT (evalStateT (gifLoopState filename fps start end options [] render) initial) world\n\ngifLoopState :: String -> Float -> Int -> Int -> Options -> [(Palette, GifDelay, Image Pixel8)] -> (Float -> StateT a (StateT World IO) ()) -> StateT a (StateT World IO) ()\ngifLoopState filename _ j n _ frames _ | j >= n = do\n    case writeGifImages filename LoopingForever frames of\n        Right zzz -> io zzz\n        Left zzz -> do\n            io $ print zzz\n            io $ forM_ frames $ \\(p, d, f) -> do\n                print (Codec.Picture.Types.imageWidth f, Codec.Picture.Types.imageHeight f)\ngifLoopState filename fps j n options frames render = do\n    window <- lift $ use mainWindow\n    let interval = fromIntegral j\n    render (interval/fps)\n    (width, height) <- lift $ use windowSize\n    pixelData <- io (mallocForeignPtrArray (fromIntegral $ width*height*3) :: IO (ForeignPtr (PixelBaseComponent PixelRGB8)))\n    (im, pa) <- io $ withForeignPtr pixelData $ \\ptr -> do\n                GL.readPixels (GL.Position 0 0) (GL.Size width height) $ GL.PixelData GL.RGB GL.UnsignedByte ptr\n                let gif = makeGif width height pixelData\n                let (im, pa) = palettize defaultPaletteOptions gif\n                return (im, pa)\n    io $ SDL.glSwapWindow window\n    events <- io SDL.pollEvents\n    quit <- lift $ mapM handleUIEvent events\n    unless (or quit) $ gifLoopState filename fps (j+1) n options ((pa, 4, im) : frames) render\n\nloop :: Options -> (Float -> SketchMonad ()) -> SketchMonad ()\nloop options render = do\n    window <- use mainWindow\n    interval <- realToFrac <$> (diffUTCTime <$> io getCurrentTime <*> use startTime)\n    render interval\n    io $ SDL.glSwapWindow window\n    events <- io SDL.pollEvents\n    quit <- mapM handleUIEvent events\n    unless (or quit) $ loop options render\n\nmainLoop :: CInt -> CInt -> CInt -> (Float -> SketchMonad ()) -> IO ()\nmainLoop width height samples render = do\n    options <- initSketch\n    world <- init (_shaderDirectory options) width height samples\n    io $ evalStateT (loop options render) world\n\nloopState :: Options -> (Float -> StateT a (StateT World IO) ()) -> StateT a (StateT World IO) ()\nloopState options render = do\n    window <- lift $ use mainWindow\n    now <- io getCurrentTime\n    start <- lift (use startTime)\n    let interval = realToFrac (diffUTCTime now start)\n    render interval\n    io $ SDL.glSwapWindow window\n    events <- io SDL.pollEvents\n    quit <- lift $ mapM handleUIEvent events\n    unless (or quit) $ loopState options render\n\nmainLoopState :: CInt -> CInt -> CInt -> a -> (Float -> StateT a (StateT World IO) ()) -> IO ()\nmainLoopState width height samples initial render = do\n    options <- initSketch\n    world <- init (_shaderDirectory options) width height samples\n    evalStateT (evalStateT (loopState options render) initial) world\n", "meta": {"hexsha": "10a2a5b4fb4db814e02e99278ca5986a77183b07", "size": 11489, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Sketch.hs", "max_stars_repo_name": "dpiponi/SketchBox", "max_stars_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-08-23T01:58:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-23T01:58:44.000Z", "max_issues_repo_path": "src/Sketch.hs", "max_issues_repo_name": "dpiponi/SketchBox", "max_issues_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Sketch.hs", "max_forks_repo_name": "dpiponi/SketchBox", "max_forks_repo_head_hexsha": "363bc8324751b526f8fb9c2ab67e2dea8d170449", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9457627119, "max_line_length": 172, "alphanum_fraction": 0.6700322047, "num_tokens": 2879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.30074559147595986, "lm_q1q2_score": 0.16442908890108596}}
{"text": "{-# LANGUAGE FlexibleInstances #-}\n\nimport Debug.Trace\n-- import Control.Monad.State.Lazy\n\nimport System.Environment (getArgs)\nimport System.IO (readFile)\nimport Data.Map.Strict (Map, (!), insert, elems, fromList, toList, findWithDefault, size, empty, member, findMin, findMax, singleton, filter)\nimport qualified Data.Map.Strict as M\nimport Data.Set (Set)\nimport qualified Data.Set as S\n--import qualified Data.Array as A\nimport Data.List (find, intercalate, intersperse, permutations, inits, tails, isPrefixOf)\nimport Data.List.Split (splitOn)\n-- import Data.Complex (Complex((:+)), realPart, imagPart) -- define my own complex\n\n-- import UI.NCurses\n-- import Data.Char (chr, ord)\n-- -- import Data.Complex (Complex((:+)))\nimport Data.Maybe (fromJust, fromMaybe, isJust)\ntype Instructions = Map Integer Integer\n\ndata ComputerState = Ready | Running | Blocked | Done\n  deriving (Show, Eq)\n\ndata Computer = Computer {\n  state :: ComputerState,\n  memory :: Map Integer Integer,\n  iptr :: Integer, -- instruction pointer\n  base :: Integer, -- base offset\n  input :: [Integer],\n  output :: [Integer],\n  time :: Integer}\n\ncomputer0 = Computer { state = Ready, memory = empty, iptr = 0, base = 0, input = [], output = [], time = 0 }\n\nrun1 :: Computer -> Computer -- (Integer, Integer) -> Instructions -> [Integer] -> [Integer]\nrun1 c\n  | state c == Ready = run1 $ c {state = Running}\n  | state c == Done = c\n  | state c == Blocked = if null (input c) then c else run1 $ c {state = Running}\n  | otherwise = -- running\n    --traceShow (iptr c, base c, memory c) $ \n    case instr `mod` 100 of\n      1 -> -- add\n        addTime $ c {iptr = i+4, memory = insert (addr 3) (arg 1 + arg 2) instructions}\n      2 -> -- multiply\n        addTime $ c {iptr = i+4, memory = insert (addr 3) (arg 1 * arg 2) instructions}\n      3 -> -- read input\n        if (null $ input c)\n        then c {state = Blocked}\n        else addTime $ c {iptr = i+2, memory = insert (addr 1) (head $ input c) instructions, input = tail $ input c}\n      4 -> -- output\n        --traceShow (arg 1) $ \n        addTime $ c {iptr = i+2, output = output c ++ [arg 1]}\n      5 -> -- jump-if-true\n        addTime $ c {iptr = if arg 1 == 0 then i+3 else arg 2}\n      6 -> -- jump-if-false\n        addTime $ c {iptr = if arg 1 == 0 then arg 2 else i+3}\n      7 -> -- less than\n        addTime $ c {iptr = i+4, memory = insert (addr 3) (if arg 1 < arg 2 then 1 else 0) instructions}\n      8 -> -- equals\n        addTime $ c {iptr = i+4, memory = insert (addr 3) (if arg 1 == arg 2 then 1 else 0) instructions}\n      9 -> -- set relative base\n        addTime $ c {iptr = i+2, base = base c + arg 1}\n      99 -> -- halt\n        addTime $ c {state = Done}\n      _ -> error \"unknown opcode\"\n  where instructions = memory c\n        i = iptr c\n        instr = instructions!i\n        ii x = findWithDefault 0 x instructions\n        arg :: Integer -> Integer\n        arg n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ ii $ i+n\n          1 -> ii $ i+n\n          2 -> ii ((ii $ i+n) + base c)\n          _ -> error \"bad argument mode\"\n        addr n = case (instr `mod` (100*10^n)) `div` (10*10^n) of\n          0 -> ii $ i+n\n          1 -> error \"address in mode 1\"\n          2 -> --trace \"address in mode 2\" $\n            ii (i+n) + base c\n          _ -> error $ \"address in unknown mode\"\n        addTime c = c{time = time c + 1}\n\nrun :: Computer -> Computer\nrun c | state c == Done = c\n      | state c == Blocked = if null (input c) then c else run $ run1 c\n      | length (output c) == 3 = c\n      | otherwise = run $ run1 c\n\ntype NAT = (Maybe (Integer, Integer), Map Int Int, Maybe Integer)\n  -- (packet, blocked computers, last y sent to computer0)\n\nchainif :: a -> [(Bool, a->a)] -> a\n-- chainif runs a value through a series of conditional transforms. If\n-- a meets a test, it is transformed and continues in the testing\n-- chain.  This makes the code look clean, by not having to explicitly\n-- give names to intermediate results.\nchainif x cfs = foldl (\\x (cond, f)-> if cond then f x else x) x cfs\n\nrunNetwork :: Map Int Computer -> Set (Integer, Int) -> NAT-> Integer\nrunNetwork computers heap (xy, blocked, y0)\n  | isDone = fromJust y0\n  | otherwise = runNetwork computers' heap'' (xy', blocked', y0')\n  where\n    ((_, i), heap') = S.deleteFindMin heap -- find the computer with lowest time\n    c = computers!i\n    hasOutput = 3 <= length (output c)\n    [addr_, x, y] = take 3 $ output c -- laziness means this won't be executed unless needed\n    addr = fromIntegral addr_\n    isBlocked = state c == Blocked && null (input c)\n    isAllBlocked = isBlocked && isJust xy && all (> 0) (M.elems blocked)\n    isDone = isAllBlocked && case (xy, y0) of\n      (Nothing, _) -> False\n      (_, Nothing) -> False\n      (Just (x,y), Just y') -> y == y'\n    c0' = (computers!0){input = (\\(x,y)->[x,y]) (fromJust xy)}\n    c' = chainif c\n      [(hasOutput, \\c -> c{output = drop 3 $ output c})\n      ,(isBlocked, \\c -> c{input = [-1]})\n      ,(isAllBlocked && i == 0, \\c -> c0')\n      ,(True, run)\n      ]\n    c2 = computers!addr\n    computers' = chainif computers \n      [(hasOutput && addr /= 255, M.insert addr $ c2{input = input c2 ++ [x,y]})\n      ,(True, M.insert i c')\n      ,(isAllBlocked && i /= 0, M.insert 0 c0')\n      ]\n    heap'' = S.insert (time c', i) heap'\n    xy' = if hasOutput && addr == 255 then Just (x, y) else xy\n    blocked' = if not isBlocked then M.insert i 0 blocked\n               else let m = M.adjust (+ 1) i blocked\n                    in if not isAllBlocked then m\n                       else M.insert 0 0 m\n    y0' = if isAllBlocked then xy >>= return . snd else y0\n\n\nmain = do\n  -- [instructionFile] <- getArgs\n  instructionStrings <- readFile \"23.input.txt\" -- instructionFile\n  let instructions = fromList . zip [0 ..] $ map read $ splitOn \",\" instructionStrings\n\n  putStrLn \"Part 2\"\n  let addrs = [0 .. 49]\n      computers = M.fromList [(i, computer0{memory=instructions, input=[fromIntegral i]}) | i <- addrs]\n      heap = S.fromList [(0,i) | i <- addrs]\n      blocked0 = M.fromList [(i, 0) | i <- addrs]\n  print $ runNetwork computers heap (Nothing, blocked0, Nothing)\n", "meta": {"hexsha": "2dc4f3bd91ce83af9754858680fd8dafc7b9f283", "size": 6167, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "23b.hs", "max_stars_repo_name": "dpatru/aoc2019", "max_stars_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-30T21:19:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T21:19:29.000Z", "max_issues_repo_path": "23b.hs", "max_issues_repo_name": "dpatru/aoc2019", "max_issues_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "23b.hs", "max_forks_repo_name": "dpatru/aoc2019", "max_forks_repo_head_hexsha": "40426b1850c465e3ec31ae9ce5dacc371011b77b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5723684211, "max_line_length": 141, "alphanum_fraction": 0.5915355927, "num_tokens": 1852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.27202455699569283, "lm_q1q2_score": 0.16428428564655848}}
{"text": "{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE OverloadedLists #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE DataKinds #-}\n\nmodule Myelin.SNN where\n\nimport Control.Monad.Trans.State\nimport Control.Monad.Trans.Class\nimport Control.Lens hiding ((.=), (*~))\nimport Control.Monad\nimport Control.Monad.Trans.Identity\n\nimport Data.Aeson\nimport Data.Aeson.Encode.Pretty\nimport Data.Aeson.TH\n\nimport Data.ByteString.Lazy.Char8 as B\nimport Data.Monoid\nimport Data.Text\nimport Data.Traversable\n\nimport Numeric.LinearAlgebra\n\nimport GHC.Generics\n\nimport Myelin.Model\nimport Myelin.Neuron\n\n-- Builder\n\n-- | The backend targets supported by Myelin\ndata ExecutionTarget =\n    Nest {\n        _minTimestep :: Float,\n        _maxTimestep :: Float\n    }\n    | BrainScaleS {\n        _wafer :: Int, -- ^ wafer to run the experiment on\n        _hicann :: Int -- ^ hicann chip to use\n    } -- ^ first generation (wafer) brainscales system\n    -- TODO: Add support for other platforms\n    -- | Spikey {\n    --     _mappingOffset :: Int -- 0..192 (really only 0 and 192 are sensible)\n    -- }\n    | SpiNNaker -- ^ SpiNNaker neuromorphic platform\n    -- | BrainScaleS2 -- ^ second generation brainscales system\n    deriving (Eq, Show)\n\n{--\nAn execution task specifies all information needed to execute a SNN\non a specific target.\n--}\ndata Task = Task {\n    _executionTarget :: ExecutionTarget, -- ^ which neuromorphic hardware or simulator to run on\n    _network :: Network, -- ^ network that should be implemented\n    _simulationTime :: Double -- ^ simulation time in milliseconds\n} deriving (Eq, Show)\n\n-- | A spiking neural network described as a list of inputs, nodes, edges and\n-- outputs. Also keeps a counter to uniquely label items in the network.\ndata Network = Network {\n    _nextId :: Int,\n    _inputs :: [Node],\n    _nodes :: [Node],\n    _edges :: [Edge],\n    _outputs :: [Node]\n} deriving (Eq, Show)\n\n-- | Information about the population in the context of data injection/retrieval\ndata PopulationVisibility = Input | Output | Hidden\n\nmakeLenses ''Network\n\ntype SNN a m = StateT Network m a\n\n-- | The initial empty network\ninitialNetwork = Network 0 [] [] [] []\n\nnewId :: Monad m => SNN Int m\nnewId = do\n    l <- use nextId\n    nextId += 1\n    return l\n\n-- | Creates a spike source array from a list of spike times in milliseconds\nspikeSourceArray :: Monad m => [Float] -> SNN Node m\nspikeSourceArray spikeTimes = do\n    id <- newId\n    let spikeSource = SpikeSourceArray spikeTimes id\n    inputs <>= [spikeSource]\n    return spikeSource\n\n-- | Creates a spike source from a poisson distribution \nspikeSourcePoisson :: Monad m => \n  Float -> -- ^ The poisson rate\n  Integer -> -- ^ The start time in milliseconds\n  SNN Node m\nspikeSourcePoisson rate start = do\n    id <- newId\n    let spikeSource = SpikeSourcePoisson rate start id\n    inputs <>= [spikeSource]\n    return spikeSource\n\n-- | Creates a population of neurons, defined by 'Myelin.Neuron.NeuronType'\npopulation :: Monad m =>\n    String -- ^ label of the population (used for printing)\n    -> Integer -- ^ size of the population\n    -> NeuronType -- ^ type of neuron\n    -> PopulationVisibility -- ^ Input, output or hidden population\n    -> SNN Node m\npopulation label i typ visibility = do\n    l <- newId\n    let pop = Population i typ label l \n    case visibility of\n      Input -> inputs <>= [pop]\n      Output -> outputs <>= [pop]\n      Hidden -> nodes <>= [pop]\n    return pop\n\n-- | Projects two 'Node's together by projecting the first node to the second\n-- node, as prescribed by the 'ProjectionEffect' \nprojection :: Monad m => ProjectionEffect -> [Node] -> [Node] -> SNN () m\nprojection proj [p0] [p1] = edges <>= [DenseProjection proj p0 p1]\nprojection proj [p0, p1] [p2] = edges <>= [MergeProjection proj (p0, p1) p2]\nprojection proj [p0] [p1, p2] = edges <>= [ReplicateProjection proj p0 (p1, p2)]\n", "meta": {"hexsha": "30e95f238952066daf232bc449c87cada5dbfe8a", "size": 3996, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Myelin/SNN.hs", "max_stars_repo_name": "volr/myelin", "max_stars_repo_head_hexsha": "aaae7ab6f6db85c60fd7940accbb834e0068752e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Myelin/SNN.hs", "max_issues_repo_name": "volr/myelin", "max_issues_repo_head_hexsha": "aaae7ab6f6db85c60fd7940accbb834e0068752e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Myelin/SNN.hs", "max_forks_repo_name": "volr/myelin", "max_forks_repo_head_hexsha": "aaae7ab6f6db85c60fd7940accbb834e0068752e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5038167939, "max_line_length": 96, "alphanum_fraction": 0.6834334334, "num_tokens": 1028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.27825679968760103, "lm_q1q2_score": 0.16280837466211265}}
{"text": "module Universe\nwhere\n\nimport Graphics.Rendering.OpenGL as OpenGL\n\nimport AObject\nimport Politics\nimport Statistics\nimport Tree\nimport OpenGLUtils\n\naobjs :: AObjTree\naobjs = Node (0.0, 0.0)\n  [ Leaf $ AObject \"Star\"       0   (Color4 0.9 0.0 0.0 1.0) 6.0 1.0 0   glVector3Null Nothing\n  , Leaf $ AObject \"Murphy's\"   10  (Color4 0.5 0.5 1.0 1.0) 2.0 1.0 28  glVector3Null (Just \"Murphy\")\n  , Leaf $ AObject \"Loki\"       250 (Color4 0.0 0.4 0.5 1.0) 4.0 1.0 55  glVector3Null (Just \"Harju\")\n  , Node (30, 115) $ \n       [Leaf $ AObject \"Harju\"         30  (Color4 0.6 0.6 0.6 1.0) 9.0 1.0 0  glVector3Null (Just \"Harju\")\n      , Leaf $ AObject \"Harju's Moon\"  30  (Color4 0.2 0.9 0.6 1.0) 0.8 1.0 25 glVector3Null (Just \"Harju\")]\n  , Leaf $ AObject \"Riesenland\" 80  (Color4 0.1 0.8 0.8 1.0) 2.0 1.0 230 glVector3Null (Just \"Riesenland\")\n  , Leaf $ AObject \"Riesenland\" 80  (Color4 0.1 0.8 0.8 1.0) 2.0 1.0 230 glVector3Null (Just \"Riesenland\")\n  , Node (180, 480) $ \n       [Leaf $ AObject \"Natail\"     180 (Color4 0.2 0.2 0.9 1.0) 1.0 1.5 60 glVector3Null (Just \"Natail\")\n      , Leaf $ AObject \"Mammoth\"    0   (Color4 0.3 0.0 0.6 1.0) 1.5 1.0 40 glVector3Null (Just \"Natail\")]\n  ]\n\nrelations = mkRelationshipMap relationsList\n\nrelationsList =\n  [((\"Murphy\",     \"Harju\"),      (Peace, -5)),\n   ((\"Murphy\",     \"Riesenland\"), (Peace, 1)),\n   ((\"Murphy\",     \"Natail\"),     (Peace, -3)),\n   ((\"Harju\",      \"Riesenland\"), (Peace, -1)),\n   ((\"Harju\",      \"Natail\"),     (Peace, 2)),\n   ((\"Riesenland\", \"Natail\"),     (Peace, 0)),\n   ((\"Murphy\",     \"Murphy\"),     (Peace, 10)),\n   ((\"Harju\",      \"Harju\"),      (Peace, 10)),\n   ((\"Riesenland\", \"Riesenland\"), (Peace, 10)),\n   ((\"Natail\",     \"Natail\"),     (Peace, 10))]\n\nrandomAllegiance :: IO String\nrandomAllegiance = chooseIO allegiances\n\nallegiances = [\"Murphy\", \"Harju\", \"Riesenland\", \"Natail\"]\n\nplalleg :: String\nplalleg = \"\"\n\ninitialAttitudes :: AttitudeMap\ninitialAttitudes = nullAttitudes allegiances\n\n\n", "meta": {"hexsha": "243fc9efb237e1a1e6a99b1cac57150df443419c", "size": 1964, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Universe.hs", "max_stars_repo_name": "anttisalonen/starrover2", "max_stars_repo_head_hexsha": "715f69d2c0ea3e213ee13b8b05f770de784c3c4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2017-01-17T15:29:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T07:10:37.000Z", "max_issues_repo_path": "src/Universe.hs", "max_issues_repo_name": "anttisalonen/starrover2", "max_issues_repo_head_hexsha": "715f69d2c0ea3e213ee13b8b05f770de784c3c4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Universe.hs", "max_forks_repo_name": "anttisalonen/starrover2", "max_forks_repo_head_hexsha": "715f69d2c0ea3e213ee13b8b05f770de784c3c4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2015-12-11T18:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T22:41:36.000Z", "avg_line_length": 37.0566037736, "max_line_length": 108, "alphanum_fraction": 0.5982688391, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.16141236332247377}}
{"text": "{-# LANGUAGE TemplateHaskell #-}\nmodule Myelin.Nest.Types.Synapse where\n{-\n\nThis file is autogenerated to regenerate it execute\n\npython python/nest/generate.py > Types.hs\n\n-}\n\nimport Control.Lens\nimport Data.Aeson.TH\n\nimport Numeric.LinearAlgebra\n\ntype Ndarray = [Float]\ntype Tuple = [Float]\ntype Str = String\n\n-- | Representation of the synapse types available in Nest\ndata Synapse =\n    BernoulliSynapse {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _p_transmit :: Float,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | BernoulliSynapseLbl {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _p_transmit :: Float,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _weight :: Float\n    }    \n    | ContDelaySynapse {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | ContDelaySynapseHpc {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | ContDelaySynapseLbl {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _weight :: Float\n    }    \n    | DiffusionConnection {\n        _delay :: Float,\n        _diffusion_factor :: Float,\n        _drift_factor :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | DiffusionConnectionLbl {\n        _delay :: Float,\n        _diffusion_factor :: Float,\n        _drift_factor :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _weight :: Float\n    }    \n    | GapJunction {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | GapJunctionLbl {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _weight :: Float\n    }    \n    | HtSynapse {\n        _delay :: Float,\n        _delta_p :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _p :: Float,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_p :: Float,\n        _weight :: Float\n    }    \n    | HtSynapseHpc {\n        _delay :: Float,\n        _delta_p :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _p :: Float,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_p :: Float,\n        _weight :: Float\n    }    \n    | HtSynapseLbl {\n        _delay :: Float,\n        _delta_p :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _p :: Float,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_p :: Float,\n        _weight :: Float\n    }    \n    | QuantalStpSynapse {\n        _n :: Float,\n        _a :: Int,\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_fac :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float\n    }    \n    | QuantalStpSynapseHpc {\n        _n :: Float,\n        _a :: Int,\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_fac :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float\n    }    \n    | QuantalStpSynapseLbl {\n        _n :: Float,\n        _a :: Int,\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_fac :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float\n    }    \n    | RateConnectionDelayed {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | RateConnectionDelayedLbl {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _weight :: Float\n    }    \n    | RateConnectionInstantaneous {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | RateConnectionInstantaneousLbl {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _weight :: Float\n    }    \n    | StaticSynapse {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | StaticSynapseHomW {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | StaticSynapseHomWHpc {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | StaticSynapseHomWLbl {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _weight :: Float\n    }    \n    | StaticSynapseHpc {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _weight :: Float\n    }    \n    | StaticSynapseLbl {\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _weight :: Float\n    }    \n    | StdpDopamineSynapse {\n        _n :: Float,\n        _a_minus :: Float,\n        _a_plus :: Float,\n        _b :: Float,\n        _c :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_c :: Float,\n        _tau_n :: Float,\n        _tau_plus :: Float,\n        _vt :: Int,\n        _weight :: Float,\n        _wmax :: Float,\n        _wmin :: Float\n    }    \n    | StdpDopamineSynapseHpc {\n        _n :: Float,\n        _a_minus :: Float,\n        _a_plus :: Float,\n        _b :: Float,\n        _c :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_c :: Float,\n        _tau_n :: Float,\n        _tau_plus :: Float,\n        _vt :: Int,\n        _weight :: Float,\n        _wmax :: Float,\n        _wmin :: Float\n    }    \n    | StdpDopamineSynapseLbl {\n        _n :: Float,\n        _a_minus :: Float,\n        _a_plus :: Float,\n        _b :: Float,\n        _c :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_c :: Float,\n        _tau_n :: Float,\n        _tau_plus :: Float,\n        _vt :: Int,\n        _weight :: Float,\n        _wmax :: Float,\n        _wmin :: Float\n    }    \n    | StdpFacetshwSynapseHom {\n        _a_acausal :: Float,\n        _a_causal :: Float,\n        _a_thresh_th :: Float,\n        _a_thresh_tl :: Float,\n        _configbit_0 :: Ndarray,\n        _configbit_1 :: Ndarray,\n        _delay :: Float,\n        _driver_readout_time :: Float,\n        _has_delay :: Bool,\n        _init_flag :: Bool,\n        _lookuptable_0 :: Ndarray,\n        _lookuptable_1 :: Ndarray,\n        _lookuptable_2 :: Ndarray,\n        _next_readout_time :: Float,\n        _no_synapses :: Int,\n        _num_connections :: Int,\n        _readout_cycle_duration :: Float,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _reset_pattern :: Ndarray,\n        _synapse_id :: Int,\n        _synapses_per_driver :: Int,\n        _tau_minus_stdp :: Float,\n        _tau_plus :: Float,\n        _weight :: Float,\n        _weight_per_lut_entry :: Float,\n        _wmax :: Float\n    }    \n    | StdpFacetshwSynapseHomHpc {\n        _a_acausal :: Float,\n        _a_causal :: Float,\n        _a_thresh_th :: Float,\n        _a_thresh_tl :: Float,\n        _configbit_0 :: Ndarray,\n        _configbit_1 :: Ndarray,\n        _delay :: Float,\n        _driver_readout_time :: Float,\n        _has_delay :: Bool,\n        _init_flag :: Bool,\n        _lookuptable_0 :: Ndarray,\n        _lookuptable_1 :: Ndarray,\n        _lookuptable_2 :: Ndarray,\n        _next_readout_time :: Float,\n        _no_synapses :: Int,\n        _num_connections :: Int,\n        _readout_cycle_duration :: Float,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _reset_pattern :: Ndarray,\n        _synapse_id :: Int,\n        _synapses_per_driver :: Int,\n        _tau_minus_stdp :: Float,\n        _tau_plus :: Float,\n        _weight :: Float,\n        _weight_per_lut_entry :: Float,\n        _wmax :: Float\n    }    \n    | StdpFacetshwSynapseHomLbl {\n        _a_acausal :: Float,\n        _a_causal :: Float,\n        _a_thresh_th :: Float,\n        _a_thresh_tl :: Float,\n        _configbit_0 :: Ndarray,\n        _configbit_1 :: Ndarray,\n        _delay :: Float,\n        _driver_readout_time :: Float,\n        _has_delay :: Bool,\n        _init_flag :: Bool,\n        _lookuptable_0 :: Ndarray,\n        _lookuptable_1 :: Ndarray,\n        _lookuptable_2 :: Ndarray,\n        _next_readout_time :: Float,\n        _no_synapses :: Int,\n        _num_connections :: Int,\n        _readout_cycle_duration :: Float,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _reset_pattern :: Ndarray,\n        _synapse_id :: Int,\n        _synapse_label :: Int,\n        _synapses_per_driver :: Int,\n        _tau_minus_stdp :: Float,\n        _tau_plus :: Float,\n        _weight :: Float,\n        _weight_per_lut_entry :: Float,\n        _wmax :: Float\n    }    \n    | StdpPlSynapseHom {\n        _lambda :: Float,\n        _mu :: Float,\n        _alpha :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_plus :: Float,\n        _weight :: Float\n    }    \n    | StdpPlSynapseHomHpc {\n        _lambda :: Float,\n        _mu :: Float,\n        _alpha :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_plus :: Float,\n        _weight :: Float\n    }    \n    | StdpPlSynapseHomLbl {\n        _lambda :: Float,\n        _mu :: Float,\n        _alpha :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_plus :: Float,\n        _weight :: Float\n    }    \n    | StdpSynapse {\n        _lambda :: Float,\n        _alpha :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _mu_minus :: Float,\n        _mu_plus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_plus :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }    \n    | StdpSynapseHom {\n        _lambda :: Float,\n        _alpha :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _mu_minus :: Float,\n        _mu_plus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_plus :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }    \n    | StdpSynapseHomHpc {\n        _lambda :: Float,\n        _alpha :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _mu_minus :: Float,\n        _mu_plus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_plus :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }    \n    | StdpSynapseHomLbl {\n        _lambda :: Float,\n        _alpha :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _mu_minus :: Float,\n        _mu_plus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_plus :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }    \n    | StdpSynapseHpc {\n        _lambda :: Float,\n        _alpha :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _mu_minus :: Float,\n        _mu_plus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_plus :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }    \n    | StdpSynapseLbl {\n        _lambda :: Float,\n        _alpha :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _mu_minus :: Float,\n        _mu_plus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_plus :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }    \n    | StdpTripletSynapse {\n        _aminus :: Float,\n        _aminus_triplet :: Float,\n        _aplus :: Float,\n        _aplus_triplet :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _kplus_triplet :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_plus :: Float,\n        _tau_plus_triplet :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }    \n    | StdpTripletSynapseHpc {\n        _aminus :: Float,\n        _aminus_triplet :: Float,\n        _aplus :: Float,\n        _aplus_triplet :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _kplus_triplet :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_plus :: Float,\n        _tau_plus_triplet :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }    \n    | StdpTripletSynapseLbl {\n        _aminus :: Float,\n        _aminus_triplet :: Float,\n        _aplus :: Float,\n        _aplus_triplet :: Float,\n        _delay :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _kplus_triplet :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_plus :: Float,\n        _tau_plus_triplet :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }    \n    | Tsodyks2Synapse {\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_fac :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float,\n        _x :: Float\n    }    \n    | Tsodyks2SynapseHpc {\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_fac :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float,\n        _x :: Float\n    }    \n    | Tsodyks2SynapseLbl {\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_fac :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float,\n        _x :: Float\n    }    \n    | TsodyksSynapse {\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_fac :: Float,\n        _tau_psc :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float,\n        _x :: Float,\n        _y :: Float\n    }    \n    | TsodyksSynapseHom {\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_fac :: Float,\n        _tau_psc :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float,\n        _x :: Float,\n        _y :: Float\n    }    \n    | TsodyksSynapseHomHpc {\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_fac :: Float,\n        _tau_psc :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float,\n        _x :: Float,\n        _y :: Float\n    }    \n    | TsodyksSynapseHomLbl {\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_fac :: Float,\n        _tau_psc :: Float,\n        _tau_rec :: Float,\n        -- _u :: Float,\n        _weight :: Float,\n        _x :: Float,\n        _y :: Float\n    }    \n    | TsodyksSynapseHpc {\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau_fac :: Float,\n        _tau_psc :: Float,\n        _tau_rec :: Float,\n        -- _U :: Float,\n        _weight :: Float,\n        _x :: Float,\n        _y :: Float\n    }    \n    | TsodyksSynapseLbl {\n        _delay :: Float,\n        _u :: Float,\n        _has_delay :: Bool,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau_fac :: Float,\n        _tau_psc :: Float,\n        _tau_rec :: Float,\n        -- _ :: Float,\n        _weight :: Float,\n        _x :: Float,\n        _y :: Float\n    }    \n    | VogelsSprekelerSynapse {\n        _alpha :: Float,\n        _delay :: Float,\n        _eta :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }\n    | VogelsSprekelerSynapseHpc {\n        _alpha :: Float,\n        _delay :: Float,\n        _eta :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _tau :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    }\n    | VogelsSprekelerSynapseLbl {\n        _alpha :: Float,\n        _delay :: Float,\n        _eta :: Float,\n        _has_delay :: Bool,\n        _kplus :: Float,\n        _num_connections :: Int,\n        _receptor_type :: Int,\n        _requires_symmetric :: Bool,\n        _synapse_label :: Int,\n        _tau :: Float,\n        _weight :: Float,\n        _wmax :: Float\n    } deriving (Show, Read, Eq, Ord)\n\nderiveJSON defaultOptions ''Synapse\nmakeLenses ''Synapse\nmakePrisms ''Synapse\n\nbernoulli_synapse = BernoulliSynapse {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _p_transmit = 1.0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 1.0\n}\nbernoulli_synapse_lbl = BernoulliSynapseLbl {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _p_transmit = 1.0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _weight = 1.0\n}\ncont_delay_synapse = ContDelaySynapse {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 1.0\n}\ncont_delay_synapse_hpc = ContDelaySynapseHpc {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 1.0\n}\ncont_delay_synapse_lbl = ContDelaySynapseLbl {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _weight = 1.0\n}\ndiffusion_connection = DiffusionConnection {\n    _delay = 1.0,\n    _diffusion_factor = 1.0,\n    _drift_factor = 1.0,\n    _has_delay = False,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 0.0\n}\ndiffusion_connection_lbl = DiffusionConnectionLbl {\n    _delay = 1.0,\n    _diffusion_factor = 1.0,\n    _drift_factor = 1.0,\n    _has_delay = False,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _weight = 0.0\n}\ngap_junction = GapJunction {\n    _delay = 1.0,\n    _has_delay = False,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = True,\n    _weight = 1.0\n}\ngap_junction_lbl = GapJunctionLbl {\n    _delay = 1.0,\n    _has_delay = False,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = True,\n    _synapse_label = -1,\n    _weight = 1.0\n}\nht_synapse = HtSynapse {\n    _delay = 1.0,\n    _delta_p = 0.125,\n    _has_delay = True,\n    _num_connections = 0,\n    _p = 1.0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_p = 500.0,\n    _weight = 1.0\n}\nht_synapse_hpc = HtSynapseHpc {\n    _delay = 1.0,\n    _delta_p = 0.125,\n    _has_delay = True,\n    _num_connections = 0,\n    _p = 1.0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_p = 500.0,\n    _weight = 1.0\n}\nht_synapse_lbl = HtSynapseLbl {\n    _delay = 1.0,\n    _delta_p = 0.125,\n    _has_delay = True,\n    _num_connections = 0,\n    _p = 1.0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_p = 500.0,\n    _weight = 1.0\n}\nquantal_stp_synapse = QuantalStpSynapse {\n    _n = 1,\n    _a = 1,\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_fac = 10.0,\n    _tau_rec = 800.0,\n    _weight = 1.0\n}\nquantal_stp_synapse_hpc = QuantalStpSynapseHpc {\n    _n = 1,\n    _a = 1,\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_fac = 10.0,\n    _tau_rec = 800.0,\n    _weight = 1.0\n}\nquantal_stp_synapse_lbl = QuantalStpSynapseLbl {\n    _n = 1,\n    _a = 1,\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_fac = 10.0,\n    _tau_rec = 800.0,\n    _weight = 1.0\n}\nrate_connection_delayed = RateConnectionDelayed {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 1.0\n}\nrate_connection_delayed_lbl = RateConnectionDelayedLbl {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _weight = 1.0\n}\nrate_connection_instantaneous = RateConnectionInstantaneous {\n    _delay = 1.0,\n    _has_delay = False,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 1.0\n}\nrate_connection_instantaneous_lbl = RateConnectionInstantaneousLbl {\n    _delay = 1.0,\n    _has_delay = False,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _weight = 1.0\n}\nstatic_synapse = StaticSynapse {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 1.0\n}\nstatic_synapse_hom_w = StaticSynapseHomW {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 1.0\n}\nstatic_synapse_hom_w_hpc = StaticSynapseHomWHpc {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 1.0\n}\nstatic_synapse_hom_w_lbl = StaticSynapseHomWLbl {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _weight = 1.0\n}\nstatic_synapse_hpc = StaticSynapseHpc {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _weight = 1.0\n}\nstatic_synapse_lbl = StaticSynapseLbl {\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _weight = 1.0\n}\nstdp_dopamine_synapse = StdpDopamineSynapse {\n    _n = 0.0,\n    _a_minus = 1.5,\n    _a_plus = 1.0,\n    _b = 0.0,\n    _c = 0.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_c = 1000.0,\n    _tau_n = 200.0,\n    _tau_plus = 20.0,\n    _vt = -1,\n    _weight = 1.0,\n    _wmax = 200.0,\n    _wmin = 0.0\n}\nstdp_dopamine_synapse_hpc = StdpDopamineSynapseHpc {\n    _n = 0.0,\n    _a_minus = 1.5,\n    _a_plus = 1.0,\n    _b = 0.0,\n    _c = 0.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_c = 1000.0,\n    _tau_n = 200.0,\n    _tau_plus = 20.0,\n    _vt = -1,\n    _weight = 1.0,\n    _wmax = 200.0,\n    _wmin = 0.0\n}\nstdp_dopamine_synapse_lbl = StdpDopamineSynapseLbl {\n    _n = 0.0,\n    _a_minus = 1.5,\n    _a_plus = 1.0,\n    _b = 0.0,\n    _c = 0.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_c = 1000.0,\n    _tau_n = 200.0,\n    _tau_plus = 20.0,\n    _vt = -1,\n    _weight = 1.0,\n    _wmax = 200.0,\n    _wmin = 0.0\n}\nstdp_facetshw_synapse_hom = StdpFacetshwSynapseHom {\n    _a_acausal = 0.0,\n    _a_causal = 0.0,\n    _a_thresh_th = 21.835,\n    _a_thresh_tl = 21.835,\n    _configbit_0 = [0, 0, 1, 0],\n    _configbit_1 = [0, 1, 0, 0],\n    _delay = 1.0,\n    _driver_readout_time = 15.0,\n    _has_delay = True,\n    _init_flag = False,\n    _lookuptable_0 = [2, 3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 15],\n    _lookuptable_1 = [0, 0, 1, 2, 3, 4, 5, 6, 7,  8,  9, 10, 10, 11, 12, 13],\n    _lookuptable_2 = [0, 1, 2, 3, 4, 5, 6, 7, 8,  9, 10, 11, 12, 13, 14, 15],\n    _next_readout_time = 0.0,\n    _no_synapses = 0,\n    _num_connections = 0,\n    _readout_cycle_duration = 0.0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _reset_pattern = [1, 1, 1, 1, 1, 1],\n    _synapse_id = 0,\n    _synapses_per_driver = 50,\n    _tau_minus_stdp = 20.0,\n    _tau_plus = 20.0,\n    _weight = 1.0,\n    _weight_per_lut_entry = 6.666666666666667,\n    _wmax = 100.0\n}\nstdp_facetshw_synapse_hom_hpc = StdpFacetshwSynapseHomHpc {\n    _a_acausal = 0.0,\n    _a_causal = 0.0,\n    _a_thresh_th = 21.835,\n    _a_thresh_tl = 21.835,\n    _configbit_0 = [0, 0, 1, 0],\n    _configbit_1 = [0, 1, 0, 0],\n    _delay = 1.0,\n    _driver_readout_time = 15.0,\n    _has_delay = True,\n    _init_flag = False,\n    _lookuptable_0 = [2, 3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 15],\n    _lookuptable_1 = [0, 0, 1, 2, 3, 4, 5, 6, 7,  8,  9, 10, 10, 11, 12, 13],\n    _lookuptable_2 = [0, 1, 2, 3, 4, 5, 6, 7, 8,  9, 10, 11, 12, 13, 14, 15],\n    _next_readout_time = 0.0,\n    _no_synapses = 0,\n    _num_connections = 0,\n    _readout_cycle_duration = 0.0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _reset_pattern = [1, 1, 1, 1, 1, 1],\n    _synapse_id = 0,\n    _synapses_per_driver = 50,\n    _tau_minus_stdp = 20.0,\n    _tau_plus = 20.0,\n    _weight = 1.0,\n    _weight_per_lut_entry = 6.666666666666667,\n    _wmax = 100.0\n}\nstdp_facetshw_synapse_hom_lbl = StdpFacetshwSynapseHomLbl {\n    _a_acausal = 0.0,\n    _a_causal = 0.0,\n    _a_thresh_th = 21.835,\n    _a_thresh_tl = 21.835,\n    _configbit_0 = [0, 0, 1, 0],\n    _configbit_1 = [0, 1, 0, 0],\n    _delay = 1.0,\n    _driver_readout_time = 15.0,\n    _has_delay = True,\n    _init_flag = False,\n    _lookuptable_0 = [ 2,  3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 15],\n    _lookuptable_1 = [ 0,  0, 1, 2, 3, 4, 5, 6, 7,  8,  9, 10, 10, 11, 12, 13],\n    _lookuptable_2 = [ 0,  1, 2, 3, 4, 5, 6, 7, 8,  9, 10, 11, 12, 13, 14, 15],\n    _next_readout_time = 0.0,\n    _no_synapses = 0,\n    _num_connections = 0,\n    _readout_cycle_duration = 0.0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _reset_pattern = [1, 1, 1, 1, 1, 1],\n    _synapse_id = 0,\n    _synapse_label = -1,\n    _synapses_per_driver = 50,\n    _tau_minus_stdp = 20.0,\n    _tau_plus = 20.0,\n    _weight = 1.0,\n    _weight_per_lut_entry = 6.666666666666667,\n    _wmax = 100.0\n}\nstdp_pl_synapse_hom = StdpPlSynapseHom {\n    _lambda = 0.1,\n    _mu = 0.4,\n    _alpha = 1.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _kplus = 0.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_plus = 20.0,\n    _weight = 1.0\n}\nstdp_pl_synapse_hom_hpc = StdpPlSynapseHomHpc {\n    _lambda = 0.1,\n    _mu = 0.4,\n    _alpha = 1.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _kplus = 0.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_plus = 20.0,\n    _weight = 1.0\n}\nstdp_pl_synapse_hom_lbl = StdpPlSynapseHomLbl {\n    _lambda = 0.1,\n    _mu = 0.4,\n    _alpha = 1.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _kplus = 0.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_plus = 20.0,\n    _weight = 1.0\n}\nstdp_synapse = StdpSynapse {\n    _lambda = 0.01,\n    _alpha = 1.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _mu_minus = 1.0,\n    _mu_plus = 1.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_plus = 20.0,\n    _weight = 1.0,\n    _wmax = 100.0\n}\nstdp_synapse_hom = StdpSynapseHom {\n    _lambda = 0.01,\n    _alpha = 1.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _kplus = 0.0,\n    _mu_minus = 1.0,\n    _mu_plus = 1.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_plus = 20.0,\n    _weight = 1.0,\n    _wmax = 100.0\n}\nstdp_synapse_hom_hpc = StdpSynapseHomHpc {\n    _lambda = 0.01,\n    _alpha = 1.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _kplus = 0.0,\n    _mu_minus = 1.0,\n    _mu_plus = 1.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_plus = 20.0,\n    _weight = 1.0,\n    _wmax = 100.0\n}\nstdp_synapse_hom_lbl = StdpSynapseHomLbl {\n    _lambda = 0.01,\n    _alpha = 1.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _kplus = 0.0,\n    _mu_minus = 1.0,\n    _mu_plus = 1.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_plus = 20.0,\n    _weight = 1.0,\n    _wmax = 100.0\n}\nstdp_synapse_hpc = StdpSynapseHpc {\n    _lambda = 0.01,\n    _alpha = 1.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _mu_minus = 1.0,\n    _mu_plus = 1.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_plus = 20.0,\n    _weight = 1.0,\n    _wmax = 100.0\n}\nstdp_synapse_lbl = StdpSynapseLbl {\n    _lambda = 0.01,\n    _alpha = 1.0,\n    _delay = 1.0,\n    _has_delay = True,\n    _mu_minus = 1.0,\n    _mu_plus = 1.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_plus = 20.0,\n    _weight = 1.0,\n    _wmax = 100.0\n}\nstdp_triplet_synapse = StdpTripletSynapse {\n    _aminus = 0.007,\n    _aminus_triplet = 0.00023,\n    _aplus = 5e-10,\n    _aplus_triplet = 0.0062,\n    _delay = 1.0,\n    _has_delay = True,\n    _kplus = 0.0,\n    _kplus_triplet = 0.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_plus = 16.8,\n    _tau_plus_triplet = 101.0,\n    _weight = 1.0,\n    _wmax = 100.0\n}\nstdp_triplet_synapse_hpc = StdpTripletSynapseHpc {\n    _aminus = 0.007,\n    _aminus_triplet = 0.00023,\n    _aplus = 5e-10,\n    _aplus_triplet = 0.0062,\n    _delay = 1.0,\n    _has_delay = True,\n    _kplus = 0.0,\n    _kplus_triplet = 0.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_plus = 16.8,\n    _tau_plus_triplet = 101.0,\n    _weight = 1.0,\n    _wmax = 100.0\n}\nstdp_triplet_synapse_lbl = StdpTripletSynapseLbl {\n    _aminus = 0.007,\n    _aminus_triplet = 0.00023,\n    _aplus = 5e-10,\n    _aplus_triplet = 0.0062,\n    _delay = 1.0,\n    _has_delay = True,\n    _kplus = 0.0,\n    _kplus_triplet = 0.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_plus = 16.8,\n    _tau_plus_triplet = 101.0,\n    _weight = 1.0,\n    _wmax = 100.0\n}\ntsodyks2_synapse = Tsodyks2Synapse {\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_fac = 0.0,\n    _tau_rec = 800.0,\n    _weight = 1.0,\n    _x = 1.0\n}\ntsodyks2_synapse_hpc = Tsodyks2SynapseHpc {\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_fac = 0.0,\n    _tau_rec = 800.0,\n    _weight = 1.0,\n    _x = 1.0\n}\ntsodyks2_synapse_lbl = Tsodyks2SynapseLbl {\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_fac = 0.0,\n    _tau_rec = 800.0,\n    _weight = 1.0,\n    _x = 1.0\n}\ntsodyks_synapse = TsodyksSynapse {\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_fac = 0.0,\n    _tau_psc = 3.0,\n    _tau_rec = 800.0,\n    _weight = 1.0,\n    _x = 1.0,\n    _y = 0.0\n}\ntsodyks_synapse_hom = TsodyksSynapseHom {\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_fac = 0.0,\n    _tau_psc = 3.0,\n    _tau_rec = 800.0,\n    _weight = 1.0,\n    _x = 1.0,\n    _y = 0.0\n}\ntsodyks_synapse_hom_hpc = TsodyksSynapseHomHpc {\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_fac = 0.0,\n    _tau_psc = 3.0,\n    _tau_rec = 800.0,\n    _weight = 1.0,\n    _x = 1.0,\n    _y = 0.0\n}\ntsodyks_synapse_hom_lbl = TsodyksSynapseHomLbl {\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_fac = 0.0,\n    _tau_psc = 3.0,\n    _tau_rec = 800.0,\n    _weight = 1.0,\n    _x = 1.0,\n    _y = 0.0\n}\ntsodyks_synapse_hpc = TsodyksSynapseHpc {\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau_fac = 0.0,\n    _tau_psc = 3.0,\n    _tau_rec = 800.0,\n    _weight = 1.0,\n    _x = 1.0,\n    _y = 0.0\n}\ntsodyks_synapse_lbl = TsodyksSynapseLbl {\n    _delay = 1.0,\n    _u = 0.5,\n    _has_delay = True,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau_fac = 0.0,\n    _tau_psc = 3.0,\n    _tau_rec = 800.0,\n    _weight = 1.0,\n    _x = 1.0,\n    _y = 0.0\n}\nvogels_sprekeler_synapse = VogelsSprekelerSynapse {\n    _alpha = 0.12,\n    _delay = 1.0,\n    _eta = 0.001,\n    _has_delay = True,\n    _kplus = 0.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau = 20.0,\n    _weight = 0.5,\n    _wmax = 1.0\n}\nvogels_sprekeler_synapse_hpc = VogelsSprekelerSynapseHpc {\n    _alpha = 0.12,\n    _delay = 1.0,\n    _eta = 0.001,\n    _has_delay = True,\n    _kplus = 0.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _tau = 20.0,\n    _weight = 0.5,\n    _wmax = 1.0\n}\nvogels_sprekeler_synapse_lbl = VogelsSprekelerSynapseLbl {\n    _alpha = 0.12,\n    _delay = 1.0,\n    _eta = 0.001,\n    _has_delay = True,\n    _kplus = 0.0,\n    _num_connections = 0,\n    _receptor_type = 0,\n    _requires_symmetric = False,\n    _synapse_label = -1,\n    _tau = 20.0,\n    _weight = 0.5,\n    _wmax = 1.0\n}", "meta": {"hexsha": "fdb4f371824578354d6b5de8573c212240400a50", "size": 37733, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/Myelin/Nest/Types/Synapse.hs", "max_stars_repo_name": "volr/myelin", "max_stars_repo_head_hexsha": "aaae7ab6f6db85c60fd7940accbb834e0068752e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Myelin/Nest/Types/Synapse.hs", "max_issues_repo_name": "volr/myelin", "max_issues_repo_head_hexsha": "aaae7ab6f6db85c60fd7940accbb834e0068752e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Myelin/Nest/Types/Synapse.hs", "max_forks_repo_name": "volr/myelin", "max_forks_repo_head_hexsha": "aaae7ab6f6db85c60fd7940accbb834e0068752e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1889185581, "max_line_length": 79, "alphanum_fraction": 0.557628601, "num_tokens": 12292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.2720245451923523, "lm_q1q2_score": 0.15605460787394193}}
{"text": "import Control.Arrow\nimport System.Directory\nimport Data.Char\nimport qualified Data.Text as T\nimport qualified Data.Text.IO as T\nimport Data.List\nimport qualified Data.Set as S\nimport qualified Data.Map.Strict as M\nimport qualified Data.IntMap.Strict as IM\nimport NLP.Stemmer\nimport Data.Ord\nimport Data.Function\nimport Data.SVM\nimport qualified Numeric.LinearAlgebra.Data as LA\nimport qualified Numeric.LinearAlgebra as LA\n\ncommon_threshold = 200\n\n-- Ratings are embedded in the file names, e.g., 100_7.txt has a rating of 7/10. Extract it.\ngetRating :: (Fractional a, Read a) => String -> a\ngetRating = (\\x -> (x-5.5)/4.5) . read . takeWhile (/= '.') . drop 1 . dropWhile (/= '_')\n\n-- Get the rating and text from all files in a directory.\nreadSamples :: (Fractional a, Read a) => String -> IO [(a, T.Text)]\nreadSamples dir = mapM ((sequence .) $ getRating &&& T.readFile . (dir++)) . filter ((/= '.') . head) =<< getDirectoryContents dir\n\n-- All of the training data, which is located across two directories.\ntrainingSamples :: (Fractional a, Read a) => IO [(a, T.Text)]\nvalidationSamples :: (Fractional a, Read a) => IO [(a, T.Text)]\n--trainingSamples = (++) <$> readSamples \"aclImdb/train/pos/\" <*> readSamples \"aclImdb/train/neg/\"\ntrainingSamples = do\n  pos <- readSamples \"aclImdb/train/pos/\"\n  neg <- readSamples \"aclImdb/train/neg/\"\n  return $ takeEvery 5 (pos ++ neg)\n\nvalidationSamples = do\n  pos <- readSamples \"aclImdb/train/pos/\"\n  neg <- readSamples \"aclImdb/train/neg/\"\n  return $ takeEvery 10 (undefined:(pos ++ neg))\n\n-- Words to ignore\nstoplist :: S.Set T.Text\nstoplist = S.fromList $ map T.pack [\"i\", \"me\", \"my\", \"she\", \"her\", \"he\", \"him\", \"his\", \"they\", \"them\", \"their\", \"it\", \"who\", \"this\", \"that\", \"which\",\n  \"\", \"br\", \"the\", \"a\", \"an\", \"is\", \"was\", \"be\", \"have\", \"are\", \"had\", \"were\", \"do\", \"did\",\n  \"and\", \"or\", \"to\", \"in\", \"for\", \"with\", \"as\", \"one\", \"at\", \"by\", \"about\", \"from\", \"other\", \"into\", \"when\", \"would\", \"than\",\n  \"also\", \"how\", \"becaus\", \"could\", \"after\", \"thing\", \"dont\", \"year\", \"two\", \"after\", \"peopl\", \"get\", \"where\", \"did\", \"off\"]\n\nminimalStoplist = S.fromList $ map T.pack [\"the\", \"a\", \"an\", \"to\", \"is\", \"that\", \"\"]\nnegateList = S.fromList $ map T.pack [\"not\", \"isnt\"]\n\n-- Word splitter which ignores puctuation and doesn't care about capitalization or apostrophes.\nwords' :: T.Text -> [T.Text]\nwords' = map (stem' English) . filter (not . T.null) . T.split (not . isAlpha) . T.toLower . T.filter (/= '\\'')\n\n-- Apply +/- modifier to word list\npreFilter :: Num a => [T.Text] -> [(a, T.Text)]\npreFilter [] = []\npreFilter (w:ws)\n  | w `S.member` negateList = alterFirst (first negate) (preFilter ws)\n  | w `S.member` minimalStoplist = preFilter ws\n  | T.pack \"un\" `T.isPrefixOf` w = (-1, T.drop 2 w) : preFilter ws\n  | T.pack \"nt\" `T.isSuffixOf` w = (-1, T.dropEnd 2 w) : preFilter ws\n  | otherwise = (1, w) : preFilter ws\n  where alterFirst f [] = []\n        alterFirst f (x:xs) = (f x) : xs\n\n-- Unify the number of occurences\nbag :: Num a => [(a, T.Text)] -> [(a, T.Text)]\nbag = map (sum . map fst &&& snd . head) . groupBy (curry $ uncurry (==) . both snd) . sortBy (comparing snd)\n\n-- The stemming method from NLP.Stemmer, wrapped up to use Text insead of String\nstem' :: Stemmer -> T.Text -> T.Text\nstem' lang = T.pack . stem lang . T.unpack\n\n-- The set of words in a dataset that meet the common threshold\ncommon :: [(a, T.Text)] -> S.Set T.Text\ncommon dataset = S.fromList . map snd . filter (\\w -> fst w * common_threshold >= datalen) $ (df (`S.notMember` stoplist) dataset)\n  where datalen = length dataset\n\n-- Number of documents with each word not excluded by filter\ndf :: (T.Text -> Bool) -> [(a, T.Text)] -> [(Int, T.Text)]\ndf' :: (T.Text -> Bool) -> [(a, T.Text)] -> [(Float, T.Text)]\ndf' wf = map (log . balance . sum . map fst &&& snd . head) . groupBy ((==) `on` snd) . sortBy (comparing snd) . concatMap (bag . filter (wf . snd) . preFilter . words' . snd)\ndf wf = map (length &&& head) . group . sort . concatMap (map head . group . sort . filter wf . map snd . preFilter . words' . snd)\n--df wf = map (length &&& head) . group . sort . concatMap (map head . group . sort . filter wf . words' . snd)\n\n-- Calculates the Delta Inverse Document Frequency of the dataset\ndidf :: (Num a, Ord a) => S.Set T.Text -> [(a, T.Text)] -> M.Map T.Text Float\ndidf legalWords dataset = uncurry (M.unionWith (+)) . both (M.fromList . map swap) .\n    (                     df' (`S.member` legalWords) . filter ((>0) . fst) &&&\n     map (first negate) . df' (`S.member` legalWords) . filter ((<0) . fst)) $ dataset\n\n\nmassCorr :: Floating a => S.Set T.Text -> [(a, T.Text)] -> M.Map T.Text a\nmassCorr legalWords dataset = let (n, ex, ex2, eys) = moments in\n    M.map (\\(ey, ey2, exy) -> (exy - ex*ey/n) / sqrt ((ex2 - ex^2/n) * (ey2 - ey^2/n))) eys\n  where initial = (0, 0, 0,                                                   -- n, E[x], E[x^2]\n                   M.fromList (zip (S.toList legalWords) $ repeat (0, 0, 0))) -- E[y], E[y^2], E[xy]\n        --updateInner (n, ex, ex2, eys) (x, (y, w)) = (n, ex, ex2, M.adjust (\\(ey, ey2, exy) -> (ey+y, ey2+y^2, exy+x*y)) w eys)\n        --updateInner :: (Float, Float, Float, M.Map T.Text (Float, Float, Float)) -> (Float, (Float, T.Text)) -> (Float, Float, Float, M.Map T.Text (Float, Float, Float))\n        updateInner (n, ex, ex2, eys) (x, (y, w)) = (n, ex, ex2, M.adjust (\\(ey, ey2, exy) -> (ey+y, ey2+y^2, exy+x*y)) w eys)\n        --updateOuter :: (Float, Float, Float, M.Map T.Text (Float, Float, Float)) -> (Float, a) -> (Float, Float, Float, M.Map T.Text (Float, Float, Float))\n        updateOuter (n, ex, ex2, eys) (x, _) = (n+1, ex+x, ex2+x^2, eys) -- TODO update this with bag\n        --tokens :: (Float, T.Text) -> [(Float, (Float, T.Text))]\n        tokens str = let wordList = preFilter . words' $ snd str; n = fromIntegral (length wordList) in\n        --tokens str = let n = fromIntegral . length . words' . snd $ str in\n            zip (repeat $ fst str) (map (first (/n)) $ bag wordList)\n            --sequence $ second (map ((/n) . fromIntegral . length &&& head) . group . sort . words') str\n        moments = foldl' (\\acc d -> foldl' updateInner (updateOuter acc d) (tokens d)) initial dataset\n\nmassCorr' :: [(Double, b)] -> LA.Matrix Double -> (LA.Vector Double, Double)\nmassCorr' ys xss = let cov = (exy - LA.scale ey ex)\n                       sx = LA.cmap sqrt (ex2 - ex^2)\n                       sy = LA.konst (sqrt $ ey2 - ey^2) w\n                   in (sx/sy, LA.dot ex (sy/sx) - ey)\n  where (n, w) = first fromIntegral $ LA.size xss\n        initial = (0, 0, LA.konst 0 w, LA.konst 0 w, LA.konst 0 w)\n        update (sy, sy2, sx, sx2, sxy) (y, xs) = (sy+y, sy2+y^2, sx+xs, sx2+xs^2, sxy + LA.scale y xs)\n        (ey, ey2, ex, ex2, exy) = (sy/n, sy2/n, LA.scale (1/n) sx, LA.scale (1/n) sx2, LA.scale (1/n) sxy)\n          where (sy, sy2, sx, sx2, sxy) = foldl' update initial $ zip (map fst ys) (LA.toRows xss)\n\n--model :: M.Map T.Text Float -> T.Text -> Float\n--model weights str = let tokens = preFilter (words' str) in\n--  (sum . map (\\(n, w) -> n * M.findWithDefault 0 w weights)) (bag tokens) / fromIntegral (length tokens)\n\nt2v :: M.Map T.Text Int -> M.Map T.Text Double -> T.Text -> LA.Vector Double\nt2v lut weights t = LA.fromList $ map (flip (IM.findWithDefault 0) (t2v' lut weights t)) [0 .. length lut - 1]\n\nt2v' :: M.Map T.Text Int -> M.Map T.Text Double -> T.Text -> IM.IntMap Double\nt2v' lut weights t = IM.fromList . map (\\(x, w) -> (lut M.! w, realToFrac $ weights M.! w * x)) . filter ((`M.member` lut) . snd) . bag . preFilter $ wordList\n  where wordList = words' t\n        n = fromIntegral $ length wordList\n-- x, can also be x * weights!w or x * weights!w / n\n\ndata2m :: M.Map T.Text Int -> M.Map T.Text Double -> [(a, T.Text)] -> LA.Matrix Double\ndata2m lut weights = LA.fromRows . map (t2v lut weights . snd)\n\nm2p :: [(Double, a)] -> LA.Matrix Double -> [(Double, IM.IntMap Double)]\nm2p dataset = zip (map (clamp . fst) dataset) . map (\\row -> IM.fromList $ map (id &&& (row LA.!)) [0 .. LA.size row - 1]) . LA.toRows\n\ncheckProblem :: Model -> [(Double, IM.IntMap Double)] -> IO [(Double, Double)]\ncheckProblem model = sequence . map (sequence . second (predict model))\n--main = do\n--  dataset <- trainingSamples\n--  putStrLn \"Data Loaded\"\n--  let legalWords = common dataset\n--  let weights = didf legalWords dataset\n--  --let weights = massCorr legalWords $ map (\\(x, t) -> (if x > 0 then 1 else -1, t)) dataset\n--  putStrLn \"word scores:\"\n--  putStrLn . show $ sortBy (comparing snd) (M.toList weights)\n--  let results = map (second $ model weights) dataset\n--  let adjustment = r2 results\n--  let results' =  map (\\(x, t) -> ((x, crop $ model weights t * fst (snd adjustment) + snd (snd adjustment)), t)) dataset\n--  let errors = sortBy (comparing $ abs . uncurry (-) . fst) results'\n--  let accuracy = fromIntegral (length $ filter (uncurry (==) . both (>0) . fst) results') / fromIntegral (length results')\n--  putStrLn $ \"r\u00b2=\" ++ show (fst adjustment) ++ \"\\taccuracy=\" ++ show accuracy\n--  putStrLn \"least accurate:\"\n--  putStrLn . show $ take 50 (reverse errors)\n\nmain = do\n  dataset <- trainingSamples\n  let legalWords = common dataset\n  let weights = realToFrac <$> didf legalWords dataset\n  --let wordIndexes = let list = S.toList legalWords -- map fst . sortBy (comparing snd) . M.toList $ weights\n  --                  in  M.fromList . (flip zip) [0..] $ take 300 list ++ take 300 (reverse list)\n  putStrLn $ \"words: (\" ++ show (length legalWords) ++ \")\"\n  --putStrLn . show $ S.toList legalWords\n  let wordIndexes = M.fromList $ zip (S.toList legalWords) [0..]\n  let (u, s, v) = LA.thinSVD (data2m wordIndexes weights dataset)\n  let nsv = 300\n  let (u', s', v') = (u LA.?? (LA.All, LA.Take nsv), LA.subVector 0 nsv s, v LA.?? (LA.All, LA.Take nsv))\n  --let (weights2, bias) = massCorr' dataset u'\n  --putStrLn . show $ (weights2, bias)\n  let dataset' = m2p dataset (u' LA.<> LA.diag s')\n  svmModel <- train (CSvc 1.5) (RBF 0.01) dataset'\n  resultsTraining <- checkProblem svmModel dataset'\n  --let resultsTraining = zip (map fst dataset) (LA.toList $ (u' LA.#> weights2) + LA.konst bias nsv)\n  validationDataset <- validationSamples\n  --let u'2 = (LA.<> v') . data2m wordIndexes weights $ validationDataset\n  --let resultsValidation = zip (map fst validationDataset) (LA.toList $ (u'2 LA.#> weights2) + LA.konst bias nsv)\n  resultsValidation <- checkProblem svmModel . m2p validationDataset . (LA.<> v') . data2m wordIndexes weights $ validationDataset\n  --let dataset' = map (\\(x, t) -> (clamp x, t2v' wordIndexes t)) dataset\n  --svmModel <- train (CSvc 10) Linear (dropEvery 5 dataset')\n  --resultsTraining <- sequence $ map (sequence . second (predict svmModel)) (dropEvery 5 $ dataset')\n  --resultsValidation <- sequence $ map (sequence . second (predict svmModel)) (takeEvery 5 $ dataset')\n  let accuracy results = let a = (length $ filter (\\(a, b) -> (a>0) == (b>0)) results)\n                             n = (length results)\n                         in show a ++ \"/\" ++ show n ++ \" (\" ++ show (100 * fromIntegral a / fromIntegral n) ++ \"%)\" -- corr=\" ++ show (r2 results)\n  putStrLn $ \"training accuracy: \" ++ accuracy resultsTraining ++ \"\\tvalidation accuracy: \" ++ accuracy resultsValidation\n\ncrop :: (Num a, Ord a) => a -> a\ncrop = max (-1) . min 1\n\nclamp :: (Num a, Ord a) => a -> a\nclamp x = if x > 0 then 1 else -1\n\nbalance :: (Ord a, Fractional a) => a -> a\nbalance x = if x > 0 then 1 + x else 1 / (1 - x)\n\ntakeEvery :: Int -> [a] -> [a]\ntakeEvery n xs = case drop (n-1) xs of (y:ys) -> y : takeEvery n ys; [] -> []\n\ndropEvery :: Int -> [a] -> [a]\ndropEvery n xs = case splitAt (n-1) xs of (x, (y:ys)) -> x ++ dropEvery n ys; (x, []) -> x\n\nr2 :: Floating a => [(a, a)] -> (a, (a, a))\nr2 points = let n = fromIntegral (length points)\n                ex = sum (map fst points) / n\n                ey = sum (map snd points) / n\n                sx = sqrt $ sum (map ((^2) . ((-)ex) . fst) points) / n\n                sy = sqrt $ sum (map ((^2) . ((-)ey) . snd) points) / n\n                cov = sum (map (\\(x, y) -> (x - ex) * (y - ey)) points) / n\n            in (cov / (sx * sy), (sx / sy, ex * sy / sx - ey))\n\nboth :: (a -> b) -> (a, a) -> (b, b)\nboth f (x, y) = (f x, f y)\n\nswap :: (a, b) -> (b, a)\nswap (x, y) = (y, x)\n", "meta": {"hexsha": "4cad3369aac420547215b8a684c4285a7e16cf48", "size": 12283, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "Scratch.hs", "max_stars_repo_name": "LyraSolomon/sentiment-analysis", "max_stars_repo_head_hexsha": "e0fe2b717dd5dc2ef8e5de97cbd4eb56993ff1c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scratch.hs", "max_issues_repo_name": "LyraSolomon/sentiment-analysis", "max_issues_repo_head_hexsha": "e0fe2b717dd5dc2ef8e5de97cbd4eb56993ff1c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Scratch.hs", "max_forks_repo_name": "LyraSolomon/sentiment-analysis", "max_forks_repo_head_hexsha": "e0fe2b717dd5dc2ef8e5de97cbd4eb56993ff1c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.8318181818, "max_line_length": 175, "alphanum_fraction": 0.5952943092, "num_tokens": 3962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.28457601028405616, "lm_q1q2_score": 0.15448586725493532}}
{"text": "{-# LANGUAGE TypeFamilies, UndecidableInstances #-}\n{-# OPTIONS_GHC -Wno-missing-methods #-}\n{-# OPTIONS_GHC -Wno-orphans #-}\n-- | Orphan instances for orthotope classes.\nmodule HordeAd.Internal.OrthotopeOrphanInstances\n  ( liftVT, liftVT2, liftVS, liftVS2\n  ) where\n\nimport Prelude\n\nimport qualified Data.Array.DynamicS as OT\nimport qualified Data.Array.ShapedS as OS\nimport           Data.MonoTraversable (Element, MonoFunctor (omap))\nimport           Numeric.LinearAlgebra (Matrix, Numeric, Vector)\nimport qualified Numeric.LinearAlgebra as HM\nimport qualified Numeric.LinearAlgebra.Devel\n\nliftVT :: Numeric r\n       => (Vector r -> Vector r)\n       -> OT.Array r -> OT.Array r\nliftVT op t = OT.fromVector (OT.shapeL t) $ op $ OT.toVector t\n\nliftVT2 :: Numeric r\n        => (Vector r -> Vector r -> Vector r)\n        -> OT.Array r -> OT.Array r -> OT.Array r\nliftVT2 op t u = OT.fromVector (OT.shapeL t) $ OT.toVector t `op` OT.toVector u\n\nliftVS :: (Numeric r, OS.Shape sh)\n       => (Vector r -> Vector r)\n       -> OS.Array sh r -> OS.Array sh r\nliftVS op t = OS.fromVector $ op $ OS.toVector t\n\nliftVS2 :: (Numeric r, OS.Shape sh)\n        => (Vector r -> Vector r -> Vector r)\n        -> OS.Array sh r -> OS.Array sh r -> OS.Array sh r\nliftVS2 op t u = OS.fromVector $ OS.toVector t `op` OS.toVector u\n\n-- These constraints force @UndecidableInstances@.\ninstance (Num (Vector r), Numeric r) => Num (OT.Array r) where\n  (+) = liftVT2 (+)\n  (-) = liftVT2 (-)\n  (*) = liftVT2 (*)\n  negate = liftVT negate\n  abs = liftVT abs\n  signum = liftVT signum\n  fromInteger = OT.constant [] . fromInteger\n\ninstance (Num (Vector r), OS.Shape sh, Numeric r) => Num (OS.Array sh r) where\n  (+) = liftVS2 (+)\n  (-) = liftVS2 (-)\n  (*) = liftVS2 (*)\n  negate = liftVS negate\n  abs = liftVS abs\n  signum = liftVS signum\n  fromInteger = OS.constant . fromInteger\n\ninstance (Num (Vector r), Numeric r, Fractional r)\n         => Fractional (OT.Array r) where\n  (/) = liftVT2 (/)\n  recip = liftVT recip\n  fromRational = OT.constant [] . fromRational\n\ninstance (Num (Vector r), OS.Shape sh, Numeric r, Fractional r)\n         => Fractional (OS.Array sh r) where\n  (/) = liftVS2 (/)\n  recip = liftVS recip\n  fromRational = OS.constant . fromRational\n\ninstance ( Floating (Vector r), Num (Vector r)\n         , Numeric r, Floating r )\n         => Floating (OT.Array r) where\n  pi = OT.constant [] pi\n  exp = liftVT exp\n  log = liftVT log\n  sqrt = liftVT sqrt\n  (**) = liftVT2 (**)\n  logBase = liftVT2 logBase\n  sin = liftVT sin\n  cos = liftVT cos\n  tan = liftVT tan\n  asin = liftVT asin\n  acos = liftVT acos\n  atan = liftVT atan\n  sinh = liftVT sinh\n  cosh = liftVT cosh\n  tanh = liftVT tanh\n  asinh = liftVT asinh\n  acosh = liftVT acosh\n  atanh = liftVT atanh\n\ninstance ( Floating (Vector r), Num (Vector r)\n         , OS.Shape sh, Numeric r, Floating r )\n         => Floating (OS.Array sh r) where\n  pi = OS.constant pi\n  exp = liftVS exp\n  log = liftVS log\n  sqrt = liftVS sqrt\n  (**) = liftVS2 (**)\n  logBase = liftVS2 logBase\n  sin = liftVS sin\n  cos = liftVS cos\n  tan = liftVS tan\n  asin = liftVS asin\n  acos = liftVS acos\n  atan = liftVS atan\n  sinh = liftVS sinh\n  cosh = liftVS cosh\n  tanh = liftVS tanh\n  asinh = liftVS asinh\n  acosh = liftVS acosh\n  atanh = liftVS atanh\n\ninstance (Real (Vector r), Numeric r, Ord r)\n         => Real (OT.Array r) where\n  toRational = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance (Real (Vector r), OS.Shape sh, Numeric r, Ord r)\n         => Real (OS.Array sh r) where\n  toRational = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance (RealFrac (Vector r), Numeric r, Fractional r, Ord r)\n         => RealFrac (OT.Array r) where\n  properFraction = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance (RealFrac (Vector r), OS.Shape sh, Numeric r, Fractional r, Ord r)\n         => RealFrac (OS.Array sh r) where\n  properFraction = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance (RealFloat (Vector r), Numeric r, Floating r, Ord r)\n         => RealFloat (OT.Array r) where\n  atan2 = liftVT2 atan2\n    -- we can be selective here and omit the other methods,\n    -- most of which don't even have a differentiable codomain\n\ninstance (RealFloat (Vector r), OS.Shape sh, Numeric r, Floating r, Ord r)\n         => RealFloat (OS.Array sh r) where\n  atan2 = liftVS2 atan2\n    -- we can be selective here and omit the other methods,\n    -- most of which don't even have a differentiable codomain\n\ntype instance Element (OT.Array r) = r\n\ntype instance Element (OS.Array sh r) = r\n\ninstance Numeric r => MonoFunctor (OT.Array r) where\n  omap = OT.mapA\n\ninstance (OS.Shape sh, Numeric r) => MonoFunctor (OS.Array sh r) where\n  omap = OS.mapA\n\n\n-- TODO: move to separate orphan module(s) at some point\n\ninstance (Num (Vector r), Numeric r, Ord r)\n         => Real (Vector r) where\n  toRational = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance (Num (Vector r), Numeric r, Fractional r, Ord r)\n         => RealFrac (Vector r) where\n  properFraction = undefined\n    -- very low priority, since these are all extremely not continuous\n\n-- TODO: is there atan2 in hmatrix or can it be computed faster than this?\ninstance ( Num (Vector r), Floating (Vector r)\n         , Numeric r, Floating r, RealFloat r, Ord r )\n         => RealFloat (Vector r) where\n  atan2 = Numeric.LinearAlgebra.Devel.zipVectorWith atan2\n    -- we can be selective here and omit the other methods,\n    -- most of which don't even have a differentiable codomain\n\n-- This instance are required by the @Real@ instance, which is required\n-- by @RealFloat@, which gives @atan2@. No idea what properties\n-- @Real@ requires here, so let it crash if it's really needed.\ninstance Numeric r => Ord (Matrix r) where\n\ninstance (Num (Vector r), Numeric r, Ord (Matrix r))\n         => Real (Matrix r) where\n  toRational = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance (Num (Vector r), Numeric r, Fractional r, Ord r, Ord (Matrix r))\n         => RealFrac (Matrix r) where\n  properFraction = undefined\n    -- very low priority, since these are all extremely not continuous\n\ninstance ( Num (Vector r), Floating (Vector r)\n         , Numeric r, Floating r, RealFloat r, Ord r, Ord (Matrix r) )\n         => RealFloat (Matrix r) where\n  atan2 = Numeric.LinearAlgebra.Devel.liftMatrix2 atan2\n    -- we can be selective here and omit the other methods,\n    -- most of which don't even have a differentiable codomain\n\ntype instance Element (Matrix r) = r\n\ntype instance Element Double = Double\n\ntype instance Element Float = Float\n\ninstance Numeric r => MonoFunctor (Matrix r) where\n  omap = HM.cmap\n\ninstance MonoFunctor Double where\n  omap f = f\n\ninstance MonoFunctor Float where\n  omap f = f\n", "meta": {"hexsha": "31c125a88bbeb022ae979a47405405da87e90a14", "size": 6903, "ext": "hs", "lang": "Haskell", "max_stars_repo_path": "src/HordeAd/Internal/OrthotopeOrphanInstances.hs", "max_stars_repo_name": "Mikolaj/horde-ad", "max_stars_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HordeAd/Internal/OrthotopeOrphanInstances.hs", "max_issues_repo_name": "Mikolaj/horde-ad", "max_issues_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22, "max_issues_repo_issues_event_min_datetime": "2022-01-27T11:10:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T12:03:54.000Z", "max_forks_repo_path": "src/HordeAd/Internal/OrthotopeOrphanInstances.hs", "max_forks_repo_name": "Mikolaj/horde-ad", "max_forks_repo_head_hexsha": "1629942418f584f6b332dac0a7053338dc3bca70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5613207547, "max_line_length": 79, "alphanum_fraction": 0.6710126032, "num_tokens": 1934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.2942149845400437, "lm_q1q2_score": 0.1528509577063581}}
