### Bifor Examples in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Provides examples for the `bifor` function, which is a variant of `bitraverse` with the structure as the first argument. It demonstrates its use with `Maybe` and list inputs. ```haskell >>> **bifor (Left []) listToMaybe (find even) **Nothing ``` ```haskell >>> **bifor (Left [1, 2, 3]) listToMaybe (find even) **Just (Left 1) ``` ```haskell >>> **bifor (Right [4, 5]) listToMaybe (find even) **Just (Right 4) ``` ```haskell >>> **bifor ([1, 2, 3], [4, 5]) listToMaybe (find even) **Just (1,4) ``` ```haskell >>> **bifor ([], [4, 5]) listToMaybe (find even) **Nothing ``` -------------------------------- ### Bisequence Examples in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Illustrates the `bisequence` function, which sequences actions within a structure. It shows examples with `Maybe` and list types, demonstrating how it combines results. ```haskell >>> **bisequence (Just 4, Nothing) **Nothing ``` ```haskell >>> **bisequence (Just 4, Just 5) **Just (4,5) ``` ```haskell >>> **bisequence ([1, 2, 3], [4, 5]) **[(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)] ``` -------------------------------- ### foldr Examples Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Provides practical examples of using the `foldr` function with different operators and data types, illustrating its behavior in boolean OR operations and string concatenation. ```haskell >>> **foldr (||) False [False, True, False] **True >>> **foldr (||) False [] **False >>> **foldr (\c acc -> acc ++ [c]) "foo" ['a', 'b', 'c', 'd'] **"foodcba" ``` -------------------------------- ### BimapAccumL Example in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Shows a basic usage example of `bimapAccumL`, demonstrating how it traverses a structure from left to right, accumulating a state and transforming elements. ```haskell >>> **bimapAccumL (\acc bool -> (acc + 1, show bool)) (\acc string -> (acc * 2, reverse string)) 3 (True, "foo") **(8,("True","oof")) ``` -------------------------------- ### Example: Transforming Arguments with `on` (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Demonstrates using the `on` function to transform arguments before applying a binary operation (tuple creation in this case) in Haskell. ```Haskell ((,) `on` (*2)) 2 3 ``` -------------------------------- ### BimapAccumR Example in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Presents a basic usage example of `bimapAccumR`, illustrating its left-to-right traversal behavior similar to `bimapAccumL` but with right-to-left accumulation. ```haskell >>> **bimapAccumR (\acc bool -> (acc + 1, show bool)) (\acc string -> (acc * 2, reverse string)) 3 (True, "foo") **(7,("True","oof")) ``` -------------------------------- ### Bitraverse Examples in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Demonstrates the basic usage of the `bitraverse` function with different input types and scenarios, showcasing its ability to traverse structures from both sides. ```haskell >>> **bitraverse listToMaybe (find odd) (Left []) **Nothing ``` ```haskell >>> **bitraverse listToMaybe (find odd) (Left [1, 2, 3]) **Just (Left 1) ``` ```haskell >>> **bitraverse listToMaybe (find odd) (Right [4, 5]) **Just (Right 5) ``` ```haskell >>> **bitraverse listToMaybe (find odd) ([1, 2, 3], [4, 5]) **Just (1,5) ``` ```haskell >>> **bitraverse listToMaybe (find odd) ([], [4, 5]) **Nothing ``` -------------------------------- ### Example: Combining Lengths with `on` (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Shows how to use the `on` function to combine the lengths of two lists using addition in Haskell. ```Haskell ((+) `on` length) [1, 2, 3] [-1] ``` -------------------------------- ### Flipped Functor Application (<&>) Example Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Provides an example of the flipped version of `<$>`, denoted as `(<&>)`, which applies a function to the value inside a functor. ```haskell (<&>) :: Functor f => f a -> (a -> b) -> f b infixl 1 # (<&>) = flip fmap ``` -------------------------------- ### Example: Splitting a List with `break` (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Provides examples of using the `break` function in Haskell to split lists based on a predicate, illustrating different scenarios including when the predicate is met early, late, or not at all. ```Haskell break (> 3) [1,2,3,4,1,2,3,4] ``` ```Haskell break (< 9) [1,2,3] ``` ```Haskell break (> 9) [1,2,3] ``` -------------------------------- ### Generate subsequences of a list in Haskell (examples) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-List Provides examples of the `subsequences` function in Haskell, showing how it generates all possible subsequences of a given list. It also highlights that this function is productive on infinite inputs. ```haskell >>> **subsequences "abc" **["","a","b","ab","c","ac","bc","abc"] >>> **take 8 $ subsequences ['a'..] **["","a","b","ab","c","ac","bc","abc"] ``` -------------------------------- ### Example: Sorting by Length using `on` (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Illustrates sorting a list of lists by their lengths using the `on` function with `compare` and `length` in Haskell. ```Haskell sortBy (compare `on` length) [[0, 1, 2], [0, 1], [], [0]] ``` -------------------------------- ### Process Creation and Management Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Process Functions for creating, starting, stopping, and managing child processes. ```APIDOC ## startProcess ### Description Launch a process based on the given `ProcessConfig`. It is recommended to use functions like `withProcessWait` that ensure `stopProcess` is called. ### Method `startProcess` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **stdin** (StreamSpec anyStreamType Handle) - Configuration for the standard input stream. - **stdout** (StreamSpec anyStreamType Handle) - Configuration for the standard output stream. - **stderr** (StreamSpec anyStreamType Handle) - Configuration for the standard error stream. ### Request Example ```haskell -- Example usage within a MonadIO context -- let config = ProcessConfig stdin stdout stderr -- process <- startProcess config ``` ### Response #### Success Response (200) - **Process stdin stdout stderr** - A handle to the started process. #### Response Example ```haskell -- A handle representing the running process -- process :: Process ByteString Handle Handle ``` ## stopProcess ### Description Close a process and release any resources acquired. This ensures `terminateProcess` is called, waits for the process to exit, and closes allocated stream resources. Throws an exception if cleanup fails. ### Method `stopProcess` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **process** (Process stdin stdout stderr) - The process handle to stop. ### Request Example ```haskell -- Assuming 'process' is a handle obtained from startProcess -- stopProcess process ``` ### Response #### Success Response (200) - **()** - Indicates successful termination and resource cleanup. #### Response Example ```haskell -- No explicit return value, indicates success by not throwing an exception. ``` ## waitExitCode ### Description Wait for the process to exit and return its `ExitCode`. ### Method `waitExitCode` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **process** (Process stdin stdout stderr) - The process handle to wait for. ### Request Example ```haskell -- Assuming 'process' is a handle obtained from startProcess -- exitCode <- waitExitCode process ``` ### Response #### Success Response (200) - **ExitCode** - The exit code of the process. #### Response Example ```haskell -- Example ExitCode value -- ExitSuccess ``` ## waitExitCodeSTM ### Description Same as `waitExitCode`, but operates within the `STM` monad. ### Method `waitExitCodeSTM` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **process** (Process stdin stdout stderr) - The process handle to wait for. ### Request Example ```haskell -- Assuming 'process' is a handle obtained from startProcess -- exitCode <- atomically $ waitExitCodeSTM process ``` ### Response #### Success Response (200) - **ExitCode** - The exit code of the process. #### Response Example ```haskell -- Example ExitCode value -- ExitFailure 1 ``` ## getExitCode ### Description Check if a process has exited and, if so, return its `ExitCode`. ### Method `getExitCode` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **process** (Process stdin stdout stderr) - The process handle to check. ### Request Example ```haskell -- Assuming 'process' is a handle obtained from startProcess -- maybeExitCode <- getExitCode process ``` ### Response #### Success Response (200) - **Maybe ExitCode** - `Just ExitCode` if the process has exited, `Nothing` otherwise. #### Response Example ```haskell -- Example: Process has exited -- Just ExitSuccess -- Example: Process is still running -- Nothing ``` ## getExitCodeSTM ### Description Same as `getExitCode`, but operates within the `STM` monad. ### Method `getExitCodeSTM` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **process** (Process stdin stdout stderr) - The process handle to check. ### Request Example ```haskell -- Assuming 'process' is a handle obtained from startProcess -- maybeExitCode <- atomically $ getExitCodeSTM process ``` ### Response #### Success Response (200) - **Maybe ExitCode** - `Just ExitCode` if the process has exited, `Nothing` otherwise. #### Response Example ```haskell -- Example: Process has exited -- Just (ExitFailure 127) -- Example: Process is still running -- Nothing ``` ``` -------------------------------- ### Haskell: Foldr Example with Function Composition Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Shows how foldr can be used with a list of functions to apply them sequentially to an initial value. ```haskell >>> **foldr id 0 [(^3), (*5), (+2)] **1000 ``` -------------------------------- ### Example: Concatenating Lists (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Provides examples of using the list concatenation operator `(++)` in Haskell, showing its behavior with non-empty, empty, and mixed lists. ```Haskell [1, 2, 3] ++ [4, 5, 6] ``` ```Haskell [] ++ [1, 2, 3] ``` ```Haskell [3, 2, 1] ++ [] ``` -------------------------------- ### Transpose a list of lists in Haskell (examples) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-List Illustrates the `transpose` function in Haskell with examples of transposing matrices. It also shows how `transpose` handles rows of different lengths by skipping elements and how it hangs indefinitely on an infinite list of empty lists. ```haskell >>> **transpose [[1,2,3],[4,5,6]] **[[1,4],[2,5],[3,6]] >>> **transpose [[10,11],[20],[],[30,31,32]] **[[10,20,30],[11,31],[32]] >>> **transpose (repeat []) *** Hangs forever * ``` -------------------------------- ### zipWith3 Examples (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-List Demonstrates the usage of zipWith3 with different data types. It combines elements from three lists using a provided function. ```haskell zipWith3 (x y z -> [x, y, z]) "123" "abc" "xyz" -- Expected output: ["1ax","2by","3cz"] zipWith3 (x y z -> (x * y) + z) [1, 2, 3] [4, 5, 6] [7, 8, 9] -- Expected output: [11,18,27] ``` -------------------------------- ### Applicative (<*) and (*>) with Parser Combinators Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude An example demonstrating the use of `*>` and `<*` with `ReadP` parser combinators for parsing strings, showing how to discard intermediate parsing results. ```haskell >>> **import Data.Char **>>> **import Text.ParserCombinators.ReadP **>>> **let p = string "my name is " *> munch1 isAlpha <* eof **>>> **readP_to_S p "my name is Simon" **[("Simon","")] ``` -------------------------------- ### liftA2 Example with Maybe Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Demonstrates `liftA2` being used with the `Maybe` `Applicative` instance to combine two `Maybe` values using a binary function. ```haskell >>> **liftA2 (,) (Just 3) (Just 5) **Just (3,5) ``` -------------------------------- ### Generate permutations of a list in Haskell (examples) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-List Illustrates the `permutations` function in Haskell with examples for strings and lists. It shows the generated permutations and demonstrates that the function is productive on infinite inputs, allowing for lazy generation of permutations. ```haskell >>> **permutations "abc" **["abc","bac","cba","bca","cab","acb"] >>> **permutations [1, 2] **[[1,2],[2,1]] >>> **permutations [] **[[]] >>> **take 6 $ map (take 3) $ permutations ['a'..] **["abc","bac","cba","bca","cab","acb"] ``` -------------------------------- ### Reverse a list in Haskell (examples) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-List Provides examples of the `reverse` function in Haskell with different list inputs, including empty lists, single-element lists, and finite lists. It also illustrates the behavior with an infinite list, which causes the function to hang. ```haskell >>> **reverse [] **[] >>> **reverse [42] **[42] >>> **reverse [2,5,7] **[7,5,2] >>> **reverse [1..] *** Hangs forever * ``` -------------------------------- ### Applicative liftA2 Function Example Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Introduces `liftA2`, which lifts a binary function to operate on two `Applicative` actions. It can be more efficient than using `<*>` and `fmap` separately. ```haskell liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c # Lift a binary function to actions. Some functors support an implementation of `liftA2` that is more efficient than the default one. In particular, if `fmap` is an expensive operation, it is likely better to use `liftA2` than to `fmap` over the structure and then use `<*>`. This became a typeclass method in 4.10.0.0. Prior to that, it was a function defined in terms of `<*>` and `fmap`. ``` -------------------------------- ### Haskell: Filter and Length Example Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Demonstrates filtering a list of booleans and calculating its length using Haskell's filter and length functions. ```haskell >>> **length $ filter id [True, True, False, True] **3 ``` -------------------------------- ### Applicative Sequence Actions (<*) Example Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Demonstrates the `<*` operator from `Applicative`, which sequences two actions but discards the result of the second action. ```haskell (<*) :: Applicative f => f a -> f b -> f a infixl 4 # Sequence actions, discarding the value of the second argument. ``` -------------------------------- ### liftA with List and Maybe Applicatives Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Provides examples of using `liftA` with the `Applicative` instances for lists and `Maybe` to apply a function to the elements within these contexts. ```haskell >>> **liftA (+1) [1, 2] **[2,3] >>> **liftA (+1) (Just 3) **Just 4 ``` -------------------------------- ### Applicative liftA Function Example Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Explains `liftA`, which lifts a function to work within an `Applicative` context. It's equivalent to `fmap` but implemented using `pure` and `<*>`. ```haskell liftA :: Applicative f => (a -> b) -> f a -> f b # Lift a function to actions. Equivalent to Functor's `fmap` but implemented using only `Applicative`'s methods: ``liftA` f a = `pure` f `<*>` a` As such this function may be used to implement a `Functor` instance from an `Applicative` one. ``` -------------------------------- ### Lens Usage Examples in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO Provides practical examples of using the 'ix' lens for accessing and modifying elements in a list. It demonstrates getting an element using '^.' and modifying an element using '&' and '%~'. ```Haskell -- Usage examples for the 'ix' lens: -- [1..9] ^. ix 3 -- [1..9] & ix 3 %~ negate ``` -------------------------------- ### Running a Simple Application with RIO Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/src/RIO This example shows how to use 'SimpleApp' from RIO for basic logging and process spawning. It requires the 'OverloadedStrings' extension for simplified logging messages. The 'runSimpleApp' function executes the RIO computation. ```haskell {-# LANGUAGE OverloadedStrings #-} module Main where main :: IO () main = runSimpleApp $ do logInfo "Hello World!" ``` -------------------------------- ### IterateN Example in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Seq Illustrates the 'iterateN' function in Haskell for constructing sequences. This function generates a sequence by repeatedly applying a given function to a starting value, up to a specified number of elements. The implementation uses 'Prelude.take' and 'Prelude.iterate'. ```Haskell iterateN n f x = fromList (Prelude.take n (Prelude.iterate f x)) ``` -------------------------------- ### for Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/doc-index-F Map each element to an action, and collect the results. ```APIDOC ## for ### Description Applies a function that returns an action to each element of a structure, and then sequences these actions, collecting their results. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Get Length of Foldable (length) in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-List The `length` function returns the size of a finite `Foldable` structure as an `Int`. Instances for structures that can compute the element count faster than via element-by-element counting should provide a specialized implementation. Example: `length ['a', 'b', 'c']` returns `3`. ```haskell length :: Foldable t => t a -> Int -- Returns the size/length of a finite structure as an `Int`. -- Example: -- >>> length [] -- 0 -- >>> length ['a', 'b', 'c'] -- 3 -- >>> length [1..] -- *** Hangs forever * ``` -------------------------------- ### Vector Access and Slicing in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Vector Illustrates how to access elements and extract subvectors (slices) from immutable vectors in Haskell. It includes functions for getting the vector's length, checking if it's empty, safe indexing, and defining slices by start index and length. ```haskell length :: Vector v a => v a -> Int null :: Vector v a => v a -> Bool (!?) :: Vector v a => v a -> Int -> Maybe a slice :: (HasCallStack, Vector v a) => Int -> Int -> v a -> v a take :: Vector v a => Int -> v a -> v a drop :: Vector v a => Int -> v a -> v a splitAt :: Vector v a => Int -> v a -> (v a, v a) ``` -------------------------------- ### Define and Run SimpleApp Environment in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude-Simple This snippet demonstrates how to define and run a SimpleApp environment in Haskell. SimpleApp provides a basic RIO environment with logging and process context. mkSimpleApp creates the environment, and runSimpleApp executes an RIO action within it. ```haskell import RIO.Prelude -- Example usage of mkSimpleApp and runSimpleApp main :: IO () main = do -- Create a SimpleApp with default logging and process context simpleApp <- mkSimpleApp logFunc Nothing -- Run an RIO action within the SimpleApp environment runRIO simpleApp $ do logInfo "This is an informational message." logDebug "This is a debug message (will only show if RIO_VERBOSE is set)." -- A more direct way to run with a default SimpleApp main' :: IO () main' = runSimpleApp $ do logInfo "Running directly with runSimpleApp." ``` -------------------------------- ### Run RIO Action with Default Process Context (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/src/src/RIO/Process Executes an RIO action using a LoggedProcessContext with default settings and no logging. It first creates a default ProcessContext and then runs the inner RIO computation within the configured environment. This is a convenient way to start a process-oriented RIO computation without explicit setup. ```haskell -- | Run an action using a 'LoggedProcessContext' with default -- settings and no logging. -- -- @since 0.0.3.0 withProcessContextNoLogging :: MonadIO m => RIO LoggedProcessContext a -> m a withProcessContextNoLogging inner = do pc <- mkDefaultProcessContext runRIO (LoggedProcessContext pc mempty) inner ``` -------------------------------- ### Right Associative Bifold (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Shows the basic usage of `bifoldr1`, a right-associative fold for non-empty bifoldable structures. It applies a binary function to combine elements, starting from the right. Examples include folding tuples, `Right`, `Left`, and `BiList`. Throws an exception on empty structures. Available since base-4.10.0.0. ```haskell bifoldr1 :: Bifoldable t => (a -> a -> a) -> t a a -> a -- Examples: -- >>> bifoldr1 (+) (5, 7) -- 12 -- >>> bifoldr1 (+) (Right 7) -- 7 -- >>> bifoldr1 (+) (Left 5) -- 5 -- >>> bifoldr1 (+) (BiList [1, 2] [3, 4]) -- 10 -- >>> bifoldr1 (+) (BiList [1, 2] []) -- 3 -- >>> bifoldr1 (+) (BiList [] []) -- ***** Exception: bifoldr1: empty structure ``` -------------------------------- ### Scan from left without initial value in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-NonEmpty A variant of `scanl` that does not take an initial accumulator value. It uses the first element of the NonEmpty stream as the starting point for the scan. Example: `scanl1 f [x1, x2, ...] == x1 :| [x1 `f` x2, x1 `f` (x2 `f` x3), ...]` ```Haskell scanl1 :: (a -> a -> a) -> NonEmpty a -> NonEmpty a ``` -------------------------------- ### RIO State Instance: get and state Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/src/test/RIO/Prelude/RIOSpec Illustrates the 'get' and 'state' functions from the RIO state instance. 'get' retrieves the current state, while 'state' allows for both getting and setting the state in a single operation. These functions are used within the RIO monad, managing mutable state via a reference. ```haskell {-# LANGUAGE OverloadedStrings#} {-# LANGUAGE NoImplicitPrelude#} module RIO.Prelude.RIOSpec (spec) where import RIO import RIO.State import RIO.Writer import Test.Hspec spec :: Spec spec = do describe "RIO state instance" $ do it "get works" $ do ref <- newSomeRef (mempty :: Text) result <- runRIO ref $ do put "hello world" get result `shouldBe` "hello world" it "state works" $ do ref <- newSomeRef (mempty :: Text) _newRef <- newSomeRef ("Hello World!" :: Text) () <- runRIO ref $ state (const ((), "Hello World!")) contents <- readSomeRef ref contents `shouldBe` "Hello World!" ``` -------------------------------- ### Haskell Import Practices with RIO Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/index Demonstrates recommended import practices when using the RIO library as a prelude replacement. It covers enabling 'NoImplicitPrelude', importing RIO itself, and using qualified imports for RIO-prefixed modules and infix operators. ```haskell {-# LANGUAGE NoImplicitPrelude #-} import RIO import qualified RIO.ByteString as B import qualified RIO.Map as Map import RIO.List ((\)) -- Example usage: main :: IO () main = do putStrLn "Hello, RIO!" let myMap = Map.fromList [(1, "one"), (2, "two")] B.putStrLn "ByteString example" let list1 = [1, 2, 3, 4] let list2 = [3, 4, 5, 6] print (list1 \ list2) ``` -------------------------------- ### Configure and Execute Process with Context (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/src/src/RIO/Process Provides a 'ProcessConfig' based on the current 'ProcessContext', handling path resolution, environment variables, and working directory. It wraps the execution with 'withProcessTimeLog' for timing and debugging. This function is analogous to 'System.Process.Typed.proc' but with IO capabilities and logging. ```haskell proc :: (HasProcessContext env, HasLogFunc env, MonadReader env m, MonadIO m, HasCallStack) => FilePath -> [String] -> (ProcessConfig () () () -> m a) -> m a proc name0 args inner = do name <- preProcess name0 wd <- view workingDirL envStrings <- view envVarsStringsL withProcessTimeLog wd name args $ inner $ setEnv envStrings $ maybe id setWorkingDir wd $ P.proc name args ``` -------------------------------- ### Run Process (Underscore Version) with MonadUnliftIO (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/src/src/RIO/Process A generalized version of 'System.Process.Typed.withProcess_' that works with 'MonadUnliftIO'. It runs a process and provides a 'Process' handle, similar to 'withProcess', but is also deprecated. Users are advised to use 'withProcessWait' or 'withProcessTerm' instead. ```haskell withProcess_ :: MonadUnliftIO m => ProcessConfig stdin stdout stderr -> (Process stdin stdout stderr -> m a) -> m a withProcess_ pc f = withRunInIO $ \run -> P.withProcessTerm_ pc (run . f) {-# DEPRECATED withProcess_ "Please consider using withProcessWait, or instead use withProcessTerm" #} ``` -------------------------------- ### unzip Examples (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-List Demonstrates the usage of the unzip function. It transforms a list of pairs into two lists: one for the first components and one for the second components. ```haskell unzip [] -- Expected output: ([],[]) unzip [(1, 'a'), (2, 'b')] -- Expected output: ([1,2],"ab") ``` -------------------------------- ### Stack Project Creation with RIO Template Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/index Command to create a new Haskell project using the 'stack' build tool, pre-configured with the RIO library. This provides a quick start for RIO-based projects. ```bash $ stack new projectname rio ``` -------------------------------- ### Applicative Sequential Application (<*>) Example Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Explains the `<*>` operator from `Applicative` for sequential application of functions within an applicative context. It's shown how it can be used with `<$>` to build complex structures like records. ```haskell (<*>) :: Applicative f => f (a -> b) -> f a -> f b infixl 4 # Sequential application. A few functors support an implementation of `<*>` that is more efficient than the default one. #### Example Expand Used in combination with `(`<$>`)`, `(`<*>`)` can be used to build a record. ``` >>> **data MyState = MyState {arg1 :: Foo, arg2 :: Bar, arg3 :: Baz} ** ``` ``` >>> **produceFoo :: Applicative f => f Foo ** ``` ``` >>> **produceBar :: Applicative f => f Bar **>>> **produceBaz :: Applicative f => f Baz ** ``` ``` >>> **mkState :: Applicative f => f MyState **>>> **mkState = MyState <$> produceFoo <*> produceBar <*> produceBaz ** ``` ``` -------------------------------- ### Getting the Length of Lazy Text in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Text-Lazy Illustrates how to get the number of characters in a lazy Text using the `length` function. It returns an `Int64` representing the character count. ```haskell length :: Text -> Int64 ``` -------------------------------- ### Cycle Taking Example in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Seq Demonstrates the 'cycleTaking' function in Haskell, which creates a sequence of a specified length by repeatedly concatenating an existing sequence. The example shows how it's implemented using 'toList', 'cycle', and 'take'. ```Haskell cycleTaking k = fromList . take k . cycle . toList ``` -------------------------------- ### Process Configuration and Streams Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Process Details on configuring processes, including setting standard input, output, and error streams. ```APIDOC ## Process Configuration and Streams ### Data Types * **data ProcessConfig stdin stdout stderr** Represents the configuration for a process. * **data StreamSpec (streamType :: StreamType) a** Specifies how a stream (input or output) should be handled. * **data StreamType** * **= STInput** * **| STOutput** * **data Process stdin stdout stderr** Represents a running process. ### Functions * **setStdin :: StreamSpec 'STInput stdin -> ProcessConfig stdin0 stdout stderr -> ProcessConfig stdin stdout stderr** Sets the standard input for a `ProcessConfig`. * **setStdout :: StreamSpec 'STOutput stdout -> ProcessConfig stdin stdout0 stderr -> ProcessConfig stdin stdout stderr** Sets the standard output for a `ProcessConfig`. ``` -------------------------------- ### unzip3 Functionality and Example (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-List The unzip3 function takes a list of triples and returns three lists containing the respective components. The example shows its behavior with an empty list and a list of triples. ```haskell unzip3 :: [(a, b, c)] -> ([a], [b], [c]) unzip3 [] -- Expected output: ([],[],[]) unzip3 [(1, 'a', True), (2, 'b', False)] -- Expected output: ([1,2],"ab",[True,False]) ``` -------------------------------- ### Create SimpleApp Instance Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/src/RIO.Prelude.Simple A constructor function `mkSimpleApp` to create a `SimpleApp` instance. It takes a `LogFunc` and an optional `ProcessContext`. If `ProcessContext` is not provided, `mkDefaultProcessContext` is used. ```haskell mkSimpleApp :: MonadIO m => LogFunc -> Maybe ProcessContext -> m SimpleApp mkSimpleApp logFunc mProcessContext = do processContext <- maybe mkDefaultProcessContext pure mProcessContext pure (SimpleApp {saLogFunc = logFunc, saProcessContext = processContext}) ``` -------------------------------- ### Intercalate lists in Haskell (examples) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-List Provides examples of the `intercalate` function in Haskell, demonstrating its use with strings and lists of numbers. It shows how `intercalate` inserts a list between elements of a list of lists and concatenates the result. ```haskell >>> **intercalate ", " ["Lorem", "ipsum", "dolor"] **"Lorem, ipsum, dolor" >>> **intercalate [0, 1] [[2, 3], [4, 5, 6], []] **[2,3,0,1,4,5,6,0,1] >>> **intercalate [1, 2, 3] [[], []] **[1,2,3] ``` -------------------------------- ### Logging Introduction in RIO Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/src/RIO This section explains RIO's logging system, which uses 'LogFunc' for plain text logging via 'HasLogFunc' and 'GLogFunc' for semantic logging via 'HasGLogFunc'. It covers basic logging functions like 'logInfo' and advanced generic logging with 'glog'. ```haskell -- $logging-intro -- -- The logging system in RIO is built upon "log functions", which are -- accessed in RIO's environment via a class like "has log -- function". There are two provided: -- -- * In the common case: for logging plain text (via 'Utf8Builder') -- efficiently, there is 'LogFunc', which can be created via -- 'withLogFunc', and is accessed via 'HasLogFunc'. This provides -- all the classical logging facilities: timestamped text output -- with log levels and colors (if terminal-supported) to the -- terminal. We log output via 'logInfo', 'logDebug', etc. -- -- * In the advanced case: where logging takes on a more semantic -- meaning and the logs need to be digested, acted upon, translated -- or serialized upstream (to e.g. a JSON logging server), we have -- 'GLogFunc' (as in "generic log function"), and is accessed via -- 'HasGLogFunc'. In this case, we log output via 'glog'. See the -- Type-generic logger section for more information. ``` -------------------------------- ### Monadic Replicate Example in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Seq Provides an example of how 'replicateA' and 'replicateM' work for sequence construction in Haskell. These functions are useful for creating sequences within applicative or monadic contexts, respectively. For newer versions of base and containers, 'replicateM' is a synonym for 'replicateA'. ```Haskell replicateA n x = sequenceA (replicate n x) replicateM n x = sequence (replicate n x) ``` -------------------------------- ### forConcurrently Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/doc-index-F Map each element to an action, and run the actions concurrently. ```APIDOC ## forConcurrently ### Description Applies a function returning an action to each element, then executes these actions concurrently, collecting their results. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### foldrDeque Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/src/RIO.Deque Folds over a Deque starting from the end. This operation does not modify the original Deque. ```APIDOC ## foldrDeque ### Description Folds over a 'Deque', starting at the end. Does not modify the 'Deque'. ### Method `foldrDeque` ### Parameters #### Type Parameters - `v`: A type constructor for mutable vectors (e.g., `Data.Vector.Unboxed.Vector`). - `m`: The prim monad. - `acc`: The accumulator type. #### Function Parameters - `f` (`a -> acc -> m acc`): The folding function. - `acc0` (`acc`): The initial accumulator value. - `deque` (`Deque v (PrimState m) a`): The deque to fold over. ### Request Example ```haskell -- Example usage (assuming appropriate imports and setup) -- foldrDeque (x acc -> pure (x : acc)) [] myDeque ``` ### Response #### Success Response - `m acc`: The final accumulated value wrapped in the prim monad. ``` -------------------------------- ### foldlDeque Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/src/RIO.Deque Folds over a Deque starting from the beginning. This operation does not modify the original Deque. ```APIDOC ## foldlDeque ### Description Folds over a 'Deque', starting at the beginning. Does not modify the 'Deque'. ### Method `foldlDeque` ### Parameters #### Type Parameters - `v`: A type constructor for mutable vectors (e.g., `Data.Vector.Unboxed.Vector`). - `m`: The prim monad. - `acc`: The accumulator type. #### Function Parameters - `f` (`acc -> a -> m acc`): The folding function. - `acc0` (`acc`): The initial accumulator value. - `deque` (`Deque v (PrimState m) a`): The deque to fold over. ### Request Example ```haskell -- Example usage (assuming appropriate imports and setup) -- foldlDeque (acc x -> pure (acc + x)) 0 myDeque ``` ### Response #### Success Response - `m acc`: The final accumulated value wrapped in the prim monad. ``` -------------------------------- ### RIO Monad Usage Example Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/index Demonstrates the correct way to use the RIO monad with typeclass constraints for environment access, contrasting it with an incorrect concrete environment approach. This promotes composability. ```haskell class HasConfig env where configL :: Lens' env Config -- more on this in a moment myFunction :: HasConfig env => RIO env Foo ``` -------------------------------- ### ByteString Length and Emptiness Check Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-ByteString Functions to get the length of a ByteString and check if it is empty. ```APIDOC ## GET /websites/hackage-content_haskell_package_rio-0_1_24_0/ByteString/length ### Description Returns the length of a ByteString as an `Int`. ### Method GET ### Endpoint `/websites/hackage-content_haskell_package_rio-0_1_24_0/ByteString/length ### Parameters #### Query Parameters - **bs** (ByteString) - Required - The ByteString to get the length of. ### Response #### Success Response (200) - **result** (Int) - The length of the ByteString. #### Response Example ```json { "result": 3 } ``` ## GET /websites/hackage-content_haskell_package_rio-0_1_24_0/ByteString/null ### Description Tests whether a ByteString is empty. ### Method GET ### Endpoint `/websites/hackage-content_haskell_package_rio-0_1_24_0/ByteString/null ### Parameters #### Query Parameters - **bs** (ByteString) - Required - The ByteString to test. ### Response #### Success Response (200) - **result** (Bool) - `True` if the ByteString is empty, `False` otherwise. #### Response Example ```json { "result": false } ``` ``` -------------------------------- ### Get the size of a HashSet Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-HashSet Demonstrates how to retrieve the number of elements in a HashSet. This operation has a time complexity of O(n). ```haskell >>> **HashSet.size HashSet.empty **0 >>> **HashSet.size (HashSet.fromList [1,2,3]) **3 ``` -------------------------------- ### Running IO from STM with join and atomically Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Demonstrates how to use `join` in conjunction with `atomically` to execute an `IO` computation that is returned from an `STM` transaction. This is necessary because `STM` transactions cannot perform `IO` directly. ```haskell join . atomically :: STM (IO b) -> IO b ``` -------------------------------- ### Get Process Handle (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Process Retrieves the underlying `ProcessHandle` for a given `Process`. This can be useful for lower-level interactions or integration with other system functions. ```Haskell unsafeProcessHandle :: Process stdin stdout stderr -> ProcessHandle ``` -------------------------------- ### Process Spawning and Execution Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Process Functions for spawning and executing child processes, including configuration, running, and waiting for process completion. ```APIDOC ## Process Spawning and Execution ### Functions * **proc :: (HasProcessContext env, HasLogFunc env, MonadReader env m, MonadIO m, HasCallStack) => FilePath -> [String] -> (ProcessConfig () () () -> m a) -> m a** Creates a `ProcessConfig` with environment overrides, path lookups, and logging enabled. * **withProcess :: MonadUnliftIO m => ProcessConfig stdin stdout stderr -> (Process stdin stdout stderr -> m a) -> m a** Runs a process with the given configuration and provides a handle to the process. * **withProcess_ :: MonadUnliftIO m => ProcessConfig stdin stdout stderr -> (Process stdin stdout stderr -> m a) -> m a** Runs a process with the given configuration and discards the handle. * **withProcessWait :: MonadUnliftIO m => ProcessConfig stdin stdout stderr -> (Process stdin stdout stderr -> m a) -> m a** Runs a process and waits for it to complete. * **withProcessWait_ :: MonadUnliftIO m => ProcessConfig stdin stdout stderr -> (Process stdin stdout stderr -> m a) -> m a** Runs a process, waits for it to complete, and discards the handle. * **withProcessTerm :: MonadUnliftIO m => ProcessConfig stdin stdout stderr -> (Process stdin stdout stderr -> m a) -> m a** Runs a process and waits for it to terminate. * **withProcessTerm_ :: MonadUnliftIO m => ProcessConfig stdin stdout stderr -> (Process stdin stdout stderr -> m a) -> m a** Runs a process, waits for it to terminate, and discards the handle. * **exec :: (HasProcessContext env, HasLogFunc env) => String -> [String] -> RIO env b** Executes a command, replacing the current process. * **execSpawn :: (HasProcessContext env, HasLogFunc env) => String -> [String] -> RIO env a** Spawns a new process to execute a command. ``` -------------------------------- ### Applicative liftA3 Function Example Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Describes `liftA3`, which lifts a ternary function to operate on three `Applicative` actions. ```haskell liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d # ``` -------------------------------- ### UnliftIO.Memoize Module Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO Documentation for the UnliftIO.Memoize module, offering memoization utilities. ```APIDOC ## UnliftIO.Memoize Module ### Description Provides utilities for memoizing function results to improve performance by caching previously computed values. ### Modules - `module UnliftIO.Memoize` ``` -------------------------------- ### Applicative pure Function Example Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Introduces the `pure` function from the `Applicative` typeclass, which lifts a value into an applicative context. ```haskell pure :: Applicative f => a -> f a # Lift a value. ``` -------------------------------- ### for_ Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/doc-index-F Map each element to an action, and discard the results. ```APIDOC ## for_ ### Description Applies a function that returns an action to each element of a structure, sequences these actions, and discards their results. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Get Length of Text in Haskell Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Text Returns the number of characters in a Text. This operation has a time complexity of O(n). ```haskell length :: Text -> Int ``` -------------------------------- ### bifor_ Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude As `bitraverse_`, but with the structure as the primary argument. ```APIDOC ## bifor_ ### Description As `bitraverse_`, but with the structure as the primary argument. For a version that doesn't ignore the results, see `bifor`. ### Method N/A (This is a typeclass method, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```haskell -- Example with a tuple bifor_ ("Hello", True) print (print . show) -- Expected output: -- "Hello" -- "True" -- Example with Right bifor_ (Right True) print (print . show) -- Expected output: -- "True" -- Example with Left bifor_ (Left "Hello") print (print . show) -- Expected output: -- "Hello" ``` ### Response #### Success Response (200) N/A (This is a function, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### Pre-process Command Execution (Haskell) Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/src/src/RIO/Process Performs pre-execution tasks for running a command, including finding the executable path and ensuring the working directory exists. It throws a 'ProcessException' if the executable cannot be found. This function is intended for internal use and is not currently exported. ```haskell preProcess :: (HasProcessContext env, MonadReader env m, MonadIO m) => String -> m FilePath preProcess name = do name' <- findExecutable name >>= either throwIO return wd <- view workingDirL liftIO $ maybe (return ()) (D.createDirectoryIfMissing True) wd return name' ``` -------------------------------- ### Haskell: Monadic Bind Example with Maybe Source: https://hackage-content.haskell.org/package/rio-0.1.24.0/docs/RIO-Prelude Illustrates the use of the monadic bind operator (>>=) with nested Maybe values in Haskell. ```haskell >>> **Just (Just 3) >>= id **Just 3 ```