packages feed

relude 0.6.0.0 → 0.7.0.0

raw patch · 66 files changed

+3073/−1409 lines, 66 filesdep −QuickCheckdep ~basedep ~ghc-primnew-uploader

Dependencies removed: QuickCheck

Dependency ranges changed: base, ghc-prim

Files

CHANGELOG.md view
@@ -3,6 +3,105 @@ `relude` uses [PVP Versioning][1]. The changelog is available [on GitHub][2]. ++## 0.7.0.0 — May 14, 2020++* [#253](https://github.com/kowainik/relude/issues/253):+  Support GHC-8.10. Upgrade GHC-8.8 to 8.8.3.+* Significant documentation improvements:+    + Add high-level description to each reexported module.+    + Add String Conversion Table.+    + Add `NonEmpty` lists functions tables.+    + Add `@since` annotations.+    + Improve README.+    + Inline some external reexports into explicit lists of exports.+    + Rewrite top-level `cabal` description.+* [#234](https://github.com/kowainik/relude/issues/234):+  Reexport `scanl1`, `scanr1`, `scanl'` from `Data.List`.+* [#256](https://github.com/kowainik/relude/issues/256):+  Make `cycle` total function.+* [#233](https://github.com/kowainik/relude/issues/233):+  Add `etaReaderT` to `Relude.Monad.Trans` to help with performance.+* [#294](https://github.com/kowainik/relude/issues/294):+  Add `atomicModifyIORef_` and `atomicModifyIORef'_`.+* [#293](https://github.com/kowainik/relude/issues/293):+  Add `memptyIfFalse` and `memptyIfTrue` functions.+* Reexport `NonEmpty` functions from `Relude.List.NonEmpty` instead of+  `Relude.List.Reexport`.+* [#239](https://github.com/kowainik/relude/issues/239):+  Reexport more STM functions that work with `TMVar` from+  `Relude.Lifted.Concurrent`.+* [#227](https://github.com/kowainik/relude/issues/227):+  Create `Relude.Extra` module+* [#228](https://github.com/kowainik/relude/issues/228):+  Add `universeNonEmpty` function.+* [#249](https://github.com/kowainik/relude/issues/249):+  __Breaking change:__ Fix infix of the `Relude.Extra.Lens` `(^.)` operator.+  Change it to `infixl 8`.+* Reexport partial `read` from `Relude.Unsafe` for consistency.+* [#244](https://github.com/kowainik/relude/issues/244):+  Remove deprecated functions: `prec`, `dupe` and `mapBoth`.++  __Migration rules:__+    + `prec`: use `prev` instead+    + `dupe`: use `dup` instead+    + `mapBoth`: use `bimapBoth` instead++* [#246](https://github.com/kowainik/relude/issues/246):+  Deprecate `Relude.Extra.Validation` in favour of+  [`validation-selective`](https://hackage.haskell.org/package/validation-selective)++  __Migration rules:__+  If you use `Relude.Extra.Validation` in you project you need to:++    1. Add `validation-selective` into the `build-depends` section of your+       `.cabal` file.+    2. Change imports of `Relude.Extra.Validation` to `Validation`:++       ```haskell+       -- Was:+       import Relude.Extra.Validation (Validation (..), ..)+       -- Became:+       import Validation (Validation (..), ..)+       ```+* [#196](https://github.com/kowainik/relude/issues/196):+  Deprecate `mapToFst` and `mapToSnd`. Introduce `toFst` and `toSnd`+  in `Relude.Extra.Tuple` as shorter aliases for `mapToFst`. Implement+  `fmapToFst` and `fmapToSnd`. Add more HLint rules for+  `Relude.Extra.Tuple` functions.++  __Migration rules:__++  + Replace `mapToFst` with `toFst`+  + Replace `mapToSnd` with `toSnd`+  + You can now use `fmapToFst` and `fmapToSnd` instead of+    `[f]map (mapToFst f)` and `[f]map (mapToSnd f)`+* [#286](https://github.com/kowainik/relude/issues/286):+  __Breaking change:__ `readEither` is not polymorphic over the first argument+  anymore. Now it takes `String`.++  __Migration rules:__ Use one of the conversion function from the+  `Relude.String.Conversion` module to covert your old input value into+  `String`.++  For example, if you had++  ```haskell+  readEither @Text @Int myText+  ```++  Now it should become:++  ```haskell+  readEither @Int (toString myText)+  ```++* [#281](https://github.com/kowainik/relude/issues/281):+  Move `One` property tests from `doctest` to `hedgehog`.+  Significant test time boost.+* [#264](https://github.com/kowainik/relude/issues/264):+  Support Dhall-16.0.0 in HLint rules.+ ## 0.6.0.0 — Oct 30, 2019  * [#171](https://github.com/kowainik/relude/issues/171):@@ -61,7 +160,7 @@ * [#172](https://github.com/kowainik/relude/issues/172):   Add `Monoid` and `Semigroup` instances for the `Validation` type.   (by [@mauriciofierrom](https://github.com/mauriciofierrom))-* [#156](https://github.com/kowainik/relude/issue/156):+* [#156](https://github.com/kowainik/relude/issues/156):   Implement helper type-level functions in `Relude.Extra.Type`.   (by [@TheMatten](https://github.com/TheMatten)) * [#170](https://github.com/kowainik/relude/issues/170):@@ -143,7 +242,7 @@   Reexport `Bitraversable` related stuff from `base`. * [#100](https://github.com/kowainik/relude/issues/100):   Add `Relude.Extra.Validation` with `Validation`data type.-* [#89](https://github.com/kowainik/relude/issues/81):+* [#89](https://github.com/kowainik/relude/issues/89):   Add `Relude.Extra.Type` module containing a `typeName` function. * [#92](https://github.com/kowainik/relude/issues/92)   Add `Relude.Extra.Tuple` module, containing@@ -166,7 +265,7 @@  * [#41](https://github.com/kowainik/relude/issues/41):   Add `Foldable1`.-* [#64](https://github.com/kowainik/relude/issues/64):+* [#63](https://github.com/kowainik/relude/issues/63):   Remove `Print` typeclass.   Add `put[L]BS[Ln]` functions.   `trace` functions now take `String` as argument instead of `Text`.
− CONTRIBUTING.md
@@ -1,53 +0,0 @@-# Contributing to the Kowainik repositories--## :wave: Greetings Traveler!--We are delighted you're reading this, and we appreciate the effort you're-taking to make our projects awesome! :sparkles:--## How to contribute--### :bug: Report bugs or feature request :bulb:--If you discover a bug or have any proposals on how to make this project better-don't hesitate to create an issue [here](../../issues/new) in a free format.--### Create a PR--We love to receive pull requests from everyone! It's usually a good idea-to tell about your intention to work on something under the corresponding-issue, so everyone is aware that you're on it. If there's no such issue — simply-create a new one!--To get started with the Pull Request implementation you should first-[fork](../../fork), then clone the repo:--    git clone git@github.com:your-username/project-name.git--Make your changes and consider the following checklist to go through-before submitting your pull request.--### :white_check_mark: Check list-- [ ] New/fixed features work as expected (Bonus points for the new tests).-- [ ] There are no warnings during compilation.-- [ ] `hlint .` output is: _No Hints_ (see [`hlint`][hlint] tool docs).-- [ ] The code is formatted with the [`stylish-haskell`][stylish-tool] tool-      using [stylish-haskell.yaml][stylish] file in the repository.-- [ ] The code style of the files you changed is preserved (for more specific-      details on our style guide check [this document][style-guide]).-- [ ] Commit messages are in the proper format.-      Start the first line of the commit with the issue number in square parentheses.--    **_Example:_** `[#42] Upgrade upper bounds of 'base'`--After all above is done commit and push to your fork.-Now you are ready to [submit a pull request](../../compare).--------------Thanks for spending your time on reading this contributing guide! :sparkling_heart:--[stylish]: .stylish-haskell.yaml-[stylish-tool]: http://hackage.haskell.org/package/stylish-haskell-[hlint]: http://hackage.haskell.org/package/hlint-[style-guide]: https://github.com/kowainik/org/blob/master/style-guide.md#haskell-style-guide
README.md view
@@ -10,145 +10,205 @@ [![Stackage Nightly](http://stackage.org/package/relude/badge/nightly)](http://stackage.org/nightly/package/relude) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -**`relude`** is an alternative prelude library. If you find the default-`Prelude` unsatisfying, despite its advantages, consider using `relude` instead.+**`relude`** is a safe, performant, user-friendly and lightweight Haskell+standard library. -Below you can find key design principles behind `relude`:+The default `Prelude` is not perfect and doesn't always satisfies one's needs.+At this stage you may want to try an alternative prelude library. In this README+we are going to give you convincing reasons to consider using `relude` as such+alternative in your next project. -1. **Avoid all** [**partial functions**](https://www.reddit.com/r/haskell/comments/5n51u3/why_are_partial_functions_as_in_head_tail_bad/)-   (like `head :: [a] -> a`). The types of partial functions lie about their-   behavior and usage of such functions can lead to the unexpected bugs. Though-   you can still use some unsafe functions from `Relude.Unsafe` module, but they-   are not exported by default.-2. **Type-safety**. We like to make invalid states unrepresentable. And if it's-   possible to express this concept through the types then we do it.+`relude` has some strong goals and principles that it sticks to. That principles+defines the library decisions and might tell you more about the priorities of+the library. So below you can find the key design principles behind `relude`: -    _Example:_+1. **Productivity.** You can be more productive with a "non-standard" standard+   library, and `relude` helps you with writing safer and more+   efficient code faster.++2. **Total programming**. Usage of+   [_partial functions_](https://www.reddit.com/r/haskell/comments/5n51u3/why_are_partial_functions_as_in_head_tail_bad/)+   can lead to unexpected bugs and runtime exceptions in pure+   code. The types of partial functions lie about their behaviour. And+   even if it is not always possible to rely only on total functions,+   `relude` strives to encourage best-practices and reduce the+   chances of introducing a bug.++  | __Partial__                     | __Total__                                  |+  |---------------------------------|--------------------------------------------|+  | `head :: [a] -> a`              | `head :: NonEmpty a -> a`                  |+  | `tail :: [a] -> [a]`            | `tail :: NonEmpty a -> [a]`                |+  | `read :: Read a => String -> a` | `readMaybe :: Read a => String -> Maybe a` |+  | `fromJust :: Maybe a -> a`      | `fromMaybe :: a -> Maybe a -> a`           |++3. **Type-safety**. We use the *"make invalid states unrepresentable"* motto as one+   of our guiding principles. If it is possible, we express this concept through the+   types.++    _Example:_ Here the function's name type and actions are aligned with each other+     ```haskell     whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f ()     ```-    instead of+    While in here, the type could represent an unreachable state:+     ```haskell     whenNotNull :: Applicative f => [a] -> ([a] -> f ()) -> f ()     ```-3. **Performance.** Prefer `Text` over [`String`](https://www.reddit.com/r/haskell/comments/29jw0s/whats_wrong_with_string/),-   use spaceleak-free functions (like our custom `sum` and `product`), introduce-   `{-# INLINE #-}` and `{-# SPECIALIZE #-}` pragmas where appropriate.-4. **Minimalism** (low number of dependencies). We don't force users of `relude` to-   stick to some specific lens or text formatting or logging library. If-   possible, `relude` tries to depend only on boot libraries.-   [Dependency graph](relude-dependency-graph.pdf) of `relude` can give you clearer picture.-5. **Convenience** (e.g lifted to `MonadIO` functions, more reexports). Despite minimalism, we-   want to bring common types and functions (like `containers` and `bytestring`)-   into scope because they are used in almost every application anyways.-6. **Provide excellent documentation.**++4. **Performance.** We prefer `Text` over [`String`](https://www.reddit.com/r/haskell/comments/29jw0s/whats_wrong_with_string/),+   use space-leaks-free functions (e.g. our custom performant `sum` and `product`), introduce+   `{-# INLINE #-}` and `{-# SPECIALIZE #-}` pragmas where+   appropriate, and make efficient container types+   (e.g. `Map`, `HashMap`, `Set`) more accesible.++5. **Minimalism** (low number of dependencies). We don not force users of+   `relude` to stick to any specific lens or text formatting or logging+   library. Where possible, `relude` depends only on boot libraries.+   The [Dependency graph](https://raw.githubusercontent.com/kowainik/relude/master/relude-dependency-graph.png)+   of `relude` can give you a clearer picture.++6. **Convenience**. Despite minimalism, we want to bring commonly used+   types and functions into scope, and make available functions easier+   to use. Some examples of conveniences:+   + No need to import types like `NonEmpty`, `Text`, `Set`, `Reader[T]`, `MVar`, `STM`+   + Functions like `liftIO`, `fromMaybe`, `sortWith` are avaiable by default as well+   + `IO` actions are lifted to `MonadIO`++7. **Excellent documentation.**    + Tutorial    + Migration guide from `Prelude`-   + Haddock for every function with examples tested by [`doctest`](http://hackage.haskell.org/package/doctest)+   + Haddock for every function with examples tested by+     [`doctest`](http://hackage.haskell.org/package/doctest)    + Documentation on [internal module structure](http://hackage.haskell.org/package/relude/docs/Relude.html)-   + `relude`-specific [HLint](http://hackage.haskell.org/package/hlint) rules: [`.hlint.yaml`](.hlint.yaml)-7. **User-friendliness.** Ability to quickly migrate to `relude` if you're familiar-   with the common libraries like `text` and `containers`.-8. **Exploration.** Experiment with new ideas and proposals without introducing-   breaking changes. `relude` uses the approach with `Extra.*` modules which are not-   exported by default so it's quite easy to bring something new and let users-   decide to use it or not.+   + `relude`-specific [HLint](http://hackage.haskell.org/package/hlint) rules:+     [`.hlint.yaml`](https://github.com/kowainik/relude/blob/master/.hlint.yaml) -This README contains introduction to `relude` and a tutorial on how to use it.+8. **User-friendliness.** Anyone should be able to quickly migrate to `relude`. Only+   some basic familiarity with the common libraries like `text` and `containers`+   should be enough (but not necessary). +9. **Exploration.** We have space to experiment with new ideas and proposals+   without introducing breaking changes. `relude` uses the approach with+   `Extra.*` modules which are not exported by default. The chosen approach makes it quite+   easy for us to provide new functionality without breaking anything and let+   the users decide to use it or not.++In addition to our key design principles, the following list of+**anti-goals** describes what `relude` is trying to avoid:++1. **Rewrite `base` from the ground up.** With `relude` you don't need+   to unlearn what you already knew, you can leverage existing+   knowledge to achieve higher productivity.+2. **Invent custom abstractions.** Learning abstractions is hard, so+   we do our best not to introduce new overwhelming concepts.+3. **Rename common definitions.** If something is called `foo` in+   `base`, it's also called `foo` in `relude`. So, `relude` doesn't+   rename any existing abstractions, but it may introduce a few new+   ones, if their benefits outweigh learning curve.++This README contains an introduction to `relude` and a tutorial on how to use it.++For a general introduction to alternative preludes, check the excellent+blog post by [Type Classes](https://typeclasses.com/) that highlights+`relude`.++* [No implicit Prelude](https://typeclasses.com/ghc/no-implicit-prelude)+ ## Structure of this tutorial  This tutorial has several parts: -1. [When to use an alternative prelude?](#when-to-use-an-alternative-prelude-)-2. [Get started](#get-started-)-    * [base-noprelude](#base-noprelude-)-    * [Mixins](#mixins-)-    * [NoImplicitPrelude](#NoImplicitPrelude-)-3. [Difference from Prelude](#difference-from-prelude-)-4. [Reexports](#reexports-)-5. [What's new?](#whats-new-)-6. [Migration guide](#migration-guide-)-7. [Comparison with other alternative preludes](#comparison-with-other-alternative-preludes-)-    * [Relude vs Protolude](#relude-vs-protolude-)-8. [For developers](#for-developers-)+1. [When to use an alternative prelude?](#when-to-use-an-alternative-prelude)+2. [Get started](#get-started)+    * [Mixins](#mixins)+    * [base-noprelude](#base-noprelude)+    * [NoImplicitPrelude](#NoImplicitPrelude)+3. [Difference from Prelude](#difference-from-prelude)+4. [Reexports](#reexports)+5. [What's new?](#whats-new)+6. [Migration guide](#migration-guide)+7. [Comparison with other alternative preludes](#comparison-with-other-alternative-preludes)+    * [Relude vs Protolude](#relude-vs-protolude)+8. [For developers](#for-developers) -This is neither a tutorial on _Haskell_ nor tutorial on each function contained-in `relude`. For detailed documentation of every function together with examples-and usage, see [_Haddock documentation_](http://hackage.haskell.org/package/relude).+This is neither a tutorial on _Haskell Standard Library_ nor a tutorial on each+function contained in `relude`. For latter see the detailed documentation of+every data type, type class and function together with examples and usages in+the [_Haddock documentation for `relude`_](http://hackage.haskell.org/package/relude). -## When to use an alternative prelude? [↑](#structure-of-this-tutorial)+## When to use an alternative prelude? +[[Back to the Table of Contents] ↑](#structure-of-this-tutorial)+ The module with the name `Prelude` is a module imported by default in every Haskell source file of your project. If you want to use some data types or functions which are not exposed by `Prelude`, you need to import them, adding necessary libraries to your project dependencies. Unlike ordinary libraries, alternative-preludes provide different set of available by default functions and data types.+preludes provide a different set of available by default functions and data+types by replacing the `Prelude` module. -Replacing default `Prelude` from `base` has the following disadvantages:+Replacing default `Prelude` from `base` has the following _disadvantages_: -1. Increased threshold entrance: you need to learn a different standard library.-    + `relude` tries to lower this threshold as much as possible: excellent-      documentation, no custom abstractions, behavior is changed only for a small-      subset of functions.+1. Increased entry threshold: you need to *learn* a different standard library.+    + `relude` tries to lower this threshold as much as possible: it comes with+      the excellent documentation, no custom abstractions, and behavior is+      changed only for a small subset of functions. 2. Extra dependencies: adding more libraries to dependencies increases build    times and maintenance burden.-   + `relude` depends only on boot libraries (almost) which results in small build time, follows-     [PvP](https://pvp.haskell.org/) and cares about backwards compatibility.+   + `relude` depends only on the boot libraries (almost) which results in small+     build time, follows [PVP](https://pvp.haskell.org/) and cares about+     backwards compatibility.  However, using an alternative prelude, specifically `relude`, has the following **advantages**:  1. Increased code safety: no partial functions, no space-leak functions. 2. Increased productivity: no need to import common functions and data types,-   more common idioms provided.-3. Increased performance: some functions in `relude` are faster than in default `Prelude`.+   more common idioms are provided.+3. Increased performance: some functions in `relude` are faster than in the+   default `Prelude`. -Our recommendations when to use `relude`:+Taking into consideration all the above points, we put together our+recommendations when to use `relude`: -1. When you develop an application (e.g. CLI tool, web-app). In that case greater-   productivity is more important than a low number of dependencies.+1. When you develop an application (e.g. CLI tool, web-app). In that case,+   greater productivity is more important than a low number of dependencies. 2. When writing a big framework. Some of them can be bigger than applications. -## Get started [↑](#structure-of-this-tutorial)+And when you may want to stay with the default standard: -If you want to start using `relude` in your project and explore it with the help-of the compiler, set everything up according to one of the instructions below.+1. When you write a small library that is supposed to be used by other people in+   their projects. -### base-noprelude [↑](#structure-of-this-tutorial)+## Get started -This is the recommended way to use custom prelude. It requires you to perform-the following steps:+[[Back to the Table of Contents] ↑](#structure-of-this-tutorial) -1. Replace the `base` dependency with corresponding version of `base-noprelude` in-   your `.cabal` file.-2. Add a `relude` dependency to your `.cabal` file.-3. Add the following `Prelude` module to your project (both to filesystem and to `exposed-modules`):-   ```haskell-   module Prelude-          ( module Relude-          ) where+If you want to start using `relude` in your project, you can set the library up+for you by one of the following ways. -   import Relude-   ```-   > **NOTE:** if you use [`summoner`](https://github.com/kowainik/summoner) to generate Haskell project,-   > this tool can automatically create such structure for you when you specify custom prelude.-4. Optionally modify your `Prelude` to include more or less functions. Probably-   you want to hide something from `Relude` module. Or maybe you want to add-   something from `Relude.Extra.*` modules!+### Mixins -This is a very convenient way to add a custom prelude to your project because-you don't need to import module manually inside each file and enable the-`NoImplicitPrelude` extension.+[[Back to the Table of Contents] ↑](#structure-of-this-tutorial) -### Mixins [↑](#structure-of-this-tutorial)+This is the recommended way to use a custom prelude. -You can use Cabal feature `mixins` to replace the default `Prelude` with `Relude`-without need to add extra dependencies or import `Relude` manually each time.-See the following example:+You can use the Cabal feature `mixins` to replace the default `Prelude` with+`Relude` without the need to add extra dependencies or to import `Relude`+manually in each module.+For this you need to add the following lines into your `.cabal` file: +```haskell+  mixins:   base hiding (Prelude)+          , relude (Relude as Prelude)+```+ > **NOTE:** this requires Cabal version to be at least `2.2` +See the following complete example of how your `.cabal` file may look+like after the set up:+ ```cabal cabal-version:       2.2 name:                prelude-example@@ -157,7 +217,7 @@ library   exposed-modules:     Example   build-depends:       base >= 4.10 && < 4.13-                     , relude ^>= 0.4.0+                     , relude ^>= 0.6.0.0    mixins:              base hiding (Prelude)                      , relude (Relude as Prelude)@@ -165,49 +225,111 @@   default-language:    Haskell2010 ``` -If you want to be able to import `Extra.*` modules when using `mixins` approach,-you need to list those modules under `mixins` field as well, like this:+> **NOTE:** if you use [`summoner`](https://github.com/kowainik/summoner) to+> generate a Haskell project, the tool automatically creates the `mixins`+> field when you specify a custom prelude. +If you want to bring a non-default module of `relude`, e.g. `Relude.Extra.Enum`+or `Relude.Unsafe`, you need to list it under the `mixins` field as well,+like this:+ ```cabal-  mixins:              base hiding (Prelude)-                     , relude (Relude as Prelude, Relude.Extra.Enum)+  mixins: base hiding (Prelude)+        , relude (Relude as Prelude+                 , Relude.Extra.Enum+                 , ...+                 ) ``` -### NoImplicitPrelude [↑](#structure-of-this-tutorial)+If you want to bring all `Extra.*` modules into scope, you can add+a single `Relude.Extra` module to `mixins`, and after that you can import all+extra functions and data types from `Relude.Extra`. This is the+easiest way to bring all functions and types from `relude` to your project+(excluding `Relude.Unsafe`). -Disable the built-in prelude at the top of your file:+```cabal+  mixins: base hiding (Prelude)+        , relude (Relude as Prelude+                 , Relude.Extra+                 )+``` +### base-noprelude++[[Back to the Table of Contents] ↑](#structure-of-this-tutorial)++Alternatively, you can use the `base-noprelude` trick to enable+alternative preludes. This approach can be helpful if you want to have+your own `Prelude` module with some custom functions, not provided by+`relude`. To use the trick, perform the following steps:++1. Replace the `base` dependency with the corresponding version of `base-noprelude` in+   your `.cabal` file.+2. Add the `relude` dependency to your `.cabal` file.+3. Create the file called `Prelude.hs` in your source directory with+   the following content:+   ```haskell+   module Prelude+       ( module Relude+       ) where++   import Relude+   ```+4. Add this module to `exposed-modules` in your `.cabal` file:+   ```cabal+   exposed-modules: Prelude+   ```+5. Optionally modify your `Prelude` module to include more or fewer functions.+   Potentially, you can hide something from the `Relude` module. Or maybe you+   want to add something from `Relude.Extra.*` modules!+   Customize the module for your needs.++This is a very convenient way to add a custom prelude to your project because+you don't need to import module manually inside each file and enable the+`NoImplicitPrelude` extension.++### NoImplicitPrelude++[[Back to the Table of Contents] ↑](#structure-of-this-tutorial)++For this option, you need to disable the default `Prelude` module first.+To disable the built-in prelude on module basis, you can add the following+pragma at the top of your file:+ ```haskell {-# LANGUAGE NoImplicitPrelude #-} ``` -Or directly in your project `.cabal` file, if you want to use in every module by-default:+if you want to disable the default `Prelude` for every module by default, you+can specify this directly in your project `.cabal` file:  ```haskell default-extensions: NoImplicitPrelude ``` -Add `relude` as a dependency of your project. Then add the following import to-your modules:+Then you need to add `relude` as a dependency of your project. +After doing all above, you can now use `Relude` in any module of your project by+adding a single import:+ ```haskell import Relude ``` -## Difference from Prelude [↑](#structure-of-this-tutorial)+## Difference from Prelude +[[Back to the Table of Contents] ↑](#structure-of-this-tutorial)+ Main differences from `Prelude` can be grouped into the following categories:  * Changed behavior of common functions   + `head`, `tail`, `last`, `init` work with `NonEmpty a` instead of `[a]`.   * `lines`, `unlines`, `words`, `unwords` work with `Text` instead of `String`.-  + `show` is polymorphic over return type.+  + `show` is polymorphic over the return type.   + Functions `sum` and `product` are strict now, which makes them more efficient.   + You can't call `elem` and `notElem` functions over `Set` and `HashSet`.-    These functions are forbidden for these two types because of the performance-    reasons.-  + `error` takes `Text`+    These functions are forbidden for these two types due to performance reasons.+  + `error` takes `Text`.   + `undefined` triggers a compiler warning, because you probably don't want to     leave `undefined` in your code. Either use `throwIO`, `Except`, `error` or     `bug`.@@ -215,19 +337,22 @@   + `read`   + `lookup` for lists   + `log`-* Completely new functions are brougth into scope-  + See [What's new?](#whats-new-) section for a detailed overview.+* Completely new functions are brought into scope+  + See the [What's new?](#whats-new) section for a detailed overview. * New reexports-  + See [Reexports](#reexports-) section for a detailed overview.+  + See the [Reexports](#reexports) section for a detailed overview. -## Reexports [↑](#structure-of-this-tutorial)+## Reexports +[[Back to the Table of Contents] ↑](#structure-of-this-tutorial)+ `relude` reexports some parts of the following libraries:  * [`base`](http://hackage.haskell.org/package/base) * [`bytestring`](http://hackage.haskell.org/package/bytestring) * [`containers`](http://hackage.haskell.org/package/containers) * [`deepseq`](http://hackage.haskell.org/package/deepseq)+* [`ghc-prim`](http://hackage.haskell.org/package/ghc-prim) * [`hashable`](http://hackage.haskell.org/package/hashable) * [`mtl`](http://hackage.haskell.org/package/mtl) * [`stm`](http://hackage.haskell.org/package/stm)@@ -235,51 +360,67 @@ * [`transformers`](http://hackage.haskell.org/package/transformers) * [`unordered-containers`](http://hackage.haskell.org/package/unordered-containers) -If you want to clean up imports after switching to `relude`, you can use-`relude`-specific [`.hlint.yaml`](.hlint.yaml) configuration for this task.+If you want to clean up your imports after switching to `relude`, you can use+the `relude`-specific+[`.hlint.yaml`](https://github.com/kowainik/relude/blob/master/.hlint.yaml)+configuration for this task. With this config, `HLint` will produce+warnings and hints on how to have more benefits from `relude`.  ### base -Multiple sorting functions are available:-  + `sortBy :: (a -> a -> Ordering) -> [a] -> [a]`: sorts list using given custom comparator.-  + `sortWith :: Ord b => (a -> b) -> [a] -> [a]`: sorts a list based on some property of its elements.-  + `sortOn :: Ord b => (a -> b) -> [a] -> [a]`: just like `sortWith`, but more+Multiple sorting functions are available for different use-cases:++  + `sortBy :: (a -> a -> Ordering) -> [a] -> [a]`: sorts a list using given+    custom comparator.+  + `sortWith :: Ord b => (a -> b) -> [a] -> [a]`: sorts a list based on some+    property of its elements.+  + `sortOn :: Ord b => (a -> b) -> [a] -> [a]`: similar to `sortWith`, but more     time-efficient if function is calculated slowly (though less     space-efficient). So you should write `sortOn length` (would sort elements     by length) but `sortWith fst` (would sort list of pairs by first element). -`readMaybe` and `readEither` are like `read` but total and give either `Maybe`-or `Either` with parse error.+`readMaybe` and `readEither` are similar to `read` but unlike it, they are total+and return either `Maybe` or `Either` with a parse error. -`(&)` – reverse application. `x & f & g` instead of `g $ f $ x` is useful sometimes.+`(&)` is the reverse application. The following three expressions are+semantically equivalent: -Some generally useful modules from `base` package, like: `Control.Applicative`,-`Data.Traversable`, `Data.Monoid`, `Data.List`, and lots of others.+* `g (f x)`+* `g $ f $ x`+* `x & f & g` +Some generally useful modules from `base` package are exported, e.g.+`Control.Applicative`, `Data.Traversable`, `Data.Monoid`, `Data.List`,+and many more.+ `liftIO` and `MonadIO` are exported by default. A lot of `IO` functions are generalized to `MonadIO`. -[`Bifunctor`](http://hackage.haskell.org/package/base-4.9.1.0/docs/Data-Bifunctor.html)+[`Bifunctor`](http://hackage.haskell.org/package/base/docs/Data-Bifunctor.html) type class with useful instances is exported. -* `first` and `second` functions apply a function to first/second part of a tuple (for tuples).-* `bimap` takes two functions and applies them to first and second parts respectively.+* `first` and `second` functions apply a function to the first and+  second part of a `Bifunctor` (`fst` and `snd` for tuples, `Left` and+  `Right` for `Either`).+* `bimap` takes two functions and applies them to the first and second parts respectively. -`trace`, `traceM`, `traceShow`, etc. are available by default. GHC will warn you-if you accidentally leave them in code, however (same for `undefined`).+`trace`, `traceM`, `traceShow`, etc. are available by default. However, GHC will+warn you if you accidentally leave them in code. Same goes for the `undefined`+function. -We also have `data Undefined = Undefined` (which, too, comes with warnings).+We also have `data Undefined = Undefined` (which also comes with the warning).  `relude` reexports `Exception` type from the `base` package and introduces the-`bug` function as an alternative to `error`. There's also a very convenient+`bug` function as an alternative to `error`. There is also a very convenient `Exc` pattern-synonym to handle exceptions of different types. -See [`Relude.Exception`](src/Relude/Exception.hs) module for details on exceptions.+See+[`Relude.Exception`](http://hackage.haskell.org/package/relude/docs/Relude-Exception.html)+module for details on exceptions.  ### containers & unordered-containers  The following types from these two packages are exported:-Then, some commonly used types:  * Maps: strict versions of `Map`, `HashMap`, `IntMap`. * Sets: `Set`, `HashSet`, `IntSet`.@@ -287,84 +428,134 @@  ### text & bytestring -`relude` exports `Text` and `ByteString` (as well as synonyms `LText` and `LByteString`-for lazy versions) and some functions work with `Text` instead of `String` –-specifically, IO functions (`readFile`, `putStrLn`, etc) and `show`. In fact, `show`-is polymorphic and can produce strict or lazy `Text`, `String`, or `ByteString`.-Also, `toText/toLText/toString` can convert `Text|LText|String` types to-`Text/LText/String`. If you want to convert to and from `ByteString` use-`encodeUtf8/decodeUtf8` functions.+`relude` exports `Text` and `ByteString` (as well as their lazy versions —+`LText` and `LByteString`). +Also, some functions now work+with `Text` instead of `String` – `words`, `lines`, etc.++In addition, `relude` provides specialised versions of the `IO` functions to+work with `Text` and `ByteString` — `readFileText`, `writeFileBS`, etc.++`show` is polymorphic and can produce strict or lazy `Text` or+`ByteString` as well as `String`.++Also, `toText|toLText|toString` can convert `Text|LText|String` types to+`Text|LText|String`. If you want to convert to and from `ByteString` use+`encodeUtf8|decodeUtf8` functions.+ ### transformers & mtl  The following parts of these two libraries are exported:  * Transformers: `State[T]`, `Reader[T]`, `ExceptT`, `MaybeT`.-* Classes: `MonadReader`, `MonadState`, `MonadError`.+* Classes: `MonadReader`, `MonadState`.  ### Deepseq -`deepseq` is exported. For instance, if you want to force deep evaluation of-some value (in `IO`), you can write `evaluateNF a`. WHNF evaluation is possible-with `evaluateWHNF a`.+All the main parts of the `deepseq` library are exported.+For instance, if you want to force the deep evaluation of+some value (in `IO`), you can write `evaluateNF a`.+Additionally, the WHNF evaluation is possible+with provided `evaluateWHNF`. -## What's new? [↑](#structure-of-this-tutorial)+## What's new? -Finally, we can move to part describing the new cool features we bring with `relude`.+[[Back to the Table of Contents] ↑](#structure-of-this-tutorial) +Finally, let's move to part describing the new cool features we bring with+`relude`.+ ### Available by default -* Safe analogue for list functions: use `viaNonEmpty` function to get `Maybe a`.-  + `viaNonEmpty head :: [a] -> Maybe a`+* Safe analogue for the list functions:+  ```haskell+  head :: NonEmpty a -> a    -- the first element of the list+  tail :: NonEmpty a -> [a]  -- the list without the first element+  last :: NonEmpty a -> a    -- the last element of the list+  init :: NonEmpty a -> [a]  -- the list without the last element+  ```++  You can also still work with lists for these functions. Using `viaNonEmpty`+  function you will get `Maybe a` from the list:++  ```haskell+  -- viaNonEmpty head :: [a] -> Maybe a+  ghci> viaNonEmpty head [1,2,3]+  Just 1+  ghci> viaNonEmpty head []+  Nothing+  ```+ * `uncons` splits a list at the first element.-* `ordNub` and `sortNub` are _O(n log n)_ versions of `nub` (which is quadratic)-  and `hashNub` and `unstableNub` are almost _O(n)_ versions of `nub`.-* `whenM`, `unlessM`, `ifM`, `guardM` are available and do what you expect-  them to do (e.g. `whenM (doesFileExist "foo")`).+* `ordNub` and `sortNub` are _O(n log n)_ versions of `nub` (which is quadratic),+  also, `hashNub` and `unstableNub` are almost _O(n)_ versions of `nub`.+* `whenM`, `unlessM`, `ifM`, `guardM` — monadic guard combinators, that work+  with any `Monad`, e.g. `whenM (doesFileExist "foo")`. * General fold functions:   ```haskell   foldMapA :: (Monoid b, Applicative m, Foldable f) => (a -> m b) -> f a -> m b   foldMapM :: (Monoid b, Monad m, Foldable f) => (a -> m b) -> f a -> m b   ```-* `when(Just|Nothing|Left|Right|NotEmpty)[M][_]`-  let you conditionally execute something. Before:+* `when(Just|Nothing|Left|Right|NotEmpty)[M][_]` functions that+  let you conditionally execute something. +  **Before:**+   ```haskell   case mbX of       Nothing -> return ()       Just x  -> f x   ``` -  After:+  **After:**    ```haskell   whenJust mbX $ \x ->       f x   ``` -* `for_` for loops. There's also `forM_` but `for_` looks a bit nicer.+* `for_` and `forM_` for loops.    ```haskell-  for_ [1..10] $ \i -> do+  for_ files $ \file -> do       ...   ``` -* `andM`, `allM`, `anyM`, `orM` are monadic version of corresponding functions from `base`.-* Conversions between `Either` and `Maybe` like `rightToMaybe` and `maybeToLeft`-  with clear semantic.+* `andM`, `allM`, `anyM`, `orM` are monadic versions of the corresponding+  functions from `base`.+* Conversions between `Either` and `Maybe`, e.g. `rightToMaybe` and `maybeToLeft`+  with clear semantics. * `using(Reader|State)[T]` functions as aliases for `flip run(Reader|State)[T]`.-* [`One` type class](src/Relude/Container/One.hs)-  for creating singleton containers. Even monomorhpic ones like `Text`.+* [`One` type class](http://hackage.haskell.org/package/relude/docs/Relude-Container-One.html)+  for creating singleton containers (even monomorphic ones like `Text`). * `evaluateWHNF` and `evaluateNF` functions as clearer and lifted aliases for   `evaluate` and `evaluate . force`. * `MonadFail` instance for `Either`. -### Need to import explicitly+### Extra bonuses +`relude` has a number of `Extra` modules that are not exposed by default (they+are not a part of the `Relude` module). You need to import such modules+separately.++These extra modules include the following functionality:+ * Convenient functions to work with `(Bounded a, Enum a)` types:   1. `universe :: (Bounded a, Enum a) => [a]`: get all values of the type.-  2. `inverseMap :: (Bounded a, Enum a, Ord k) => (a -> k) -> k -> Maybe a`: convert functions like `show` to parsers. +     ```haskell+     ghci> universe @Bool+     [True,False]+     ```+  2. `inverseMap :: (Bounded a, Enum a, Ord k) => (a -> k) -> k -> Maybe a`:+     convert functions like `show` to parsers:++     ```haskell+     readMyEnums :: Text -> Maybe MyEnum+     readMyEnums = inverseMap myShow+     ```+ * Nice helpers to deal with `newtype`s in a more pleasant way:    ```haskell@@ -376,40 +567,45 @@ * Functions to operate with `CallStack`:    ```haskell-  >>> foo :: HasCallStack => String; foo = ownName-  >>> foo+  ghci> foo :: HasCallStack => String; foo = ownName+  ghci> foo   "foo"   ```  * `Foldable1` typeclass that contains generalized interface for folding   non-empty structures like `NonEmpty`.-* `Validation` data type as an alternative to `Either` when you want to combine-  all errors. * [`StaticMap` and `DynamicMap` type classes](src/Relude/Extra/Map.hs) as a   general interface for `Map`-like data structures.+* And much more! -Explore `Extra` modules: [`Relude.Extra`](src/Relude/Extra/)+Explore `Extra` modules: [`Relude.Extra`](http://hackage.haskell.org/package/relude/docs/Relude-Extra.html) -## Migration guide [↑](#structure-of-this-tutorial)+## Migration guide -In order to replace default `Prelude` with `relude` you should start with instructions given in-[_get started_](#get-started-) section.+[[Back to the Table of Contents] ↑](#structure-of-this-tutorial) +This section of the guide helps to migrate your project from `base`+to the `relude` library.++In order to replace the default `Prelude` with `relude` you should start with+instructions provided in the  [_Get Started_](#get-started) section.+ ### Code changes  This section describes what you need to change to make your code compile with `relude`.  1. Enable `-XOverloadedStrings` extension by default for your project. 2. Since `head`, `tail`, `last` and `init` work for `NonEmpty` you should-   refactor your code in one of the multiple ways described below:+   refactor your code in one of the described below ways:    1. Change `[a]` to `NonEmpty a` where it makes sense.    2. Use functions which return `Maybe`. There is the `viaNonEmpty` function for this.       And you can use it like `viaNonEmpty last l`.        + `tail` is `drop 1`. It's almost never a good idea to use `tail` from `Prelude`.-   3. Add `import qualified Relude.Unsafe as Unsafe` and replace function with qualified usage.-3. If you use `fromJust` or `!!` you should use them from `import qualified Relude.Unsafe as Unsafe`.+   3. Add `import qualified Relude.Unsafe as Unsafe` and replace the function+      with its qualified usage: `Unsafe.head`.+3. If you use `fromJust` or `!!` you should import them from `import qualified Relude.Unsafe as Unsafe`. 4. If you use `foldr` or `forM_` or similar for something like `Maybe a` or-   `Either a b` it's recommended to replace usages of such function with+   `Either a b` it is recommended to replace usages of such functions with the    monomorhpic alternatives:    * `Maybe`      + `(?:)          :: Maybe a -> a -> a`@@ -427,16 +623,23 @@      + `whenRight_  :: Applicative f => Either l r -> (r -> f ()) -> f ()`      + `whenRightM_ :: Monad m => m (Either l r) -> (r -> m ()) -> m ()` -5. Forget about `String` type.+5. Replace the `String` type with more efficient and suitable ones (e.g. `Text`):    + Replace `(++)` with `(<>)` for `String`-like types.    + Use `toText/toLText/toString` functions to convert to `Text/LazyText/String` types.    + Use `encodeUtf8/decodeUtf8` to convert to/from `ByteString`.    + Use `(putStr[Ln]|readFile|writeFile|appendFile)[Text|LText|BS|LBS]` functions.  6. Since `show` doesn't come from `Show` anymore, you need to export-  `Text.Show` module if you want to implement `Show` instance manually. This can be done like this:+  `Text.Show` module if you want to implement `Show` instance manually. This can be done in the following way:+   ```haskell   import qualified Text.Show++  data MyType = ...++  instance Show MyType where+      show :: MyType -> String+      show = ...   ```  7. Run `hlint` using `.hlint.yaml` file from `relude` package to cleanup code and imports.@@ -461,55 +664,66 @@ curl -sSL https://raw.github.com/ndmitchell/neil/master/misc/travis.sh | sh -s -- hlint -h .hlint-relude.yaml . ``` -See an example of this feature being used in [Summoner](https://github.com/kowainik/summoner/blob/b6c3ecb7cd9bc8d1451e2cc78cd020cd2e473564/.travis.yml#L58-L59).+See an example of this feature described in the following blog post+about Travis CI settings: -## Comparison with other alternative preludes [↑](#structure-of-this-tutorial)+* [Kodimensional: Dead simple Haskell Travis settings for cabal and stack](https://kodimensional.dev/posts/2019-02-25-haskell-travis#customization-hlint) +## Comparison with other alternative preludes++[[Back to the Table of Contents] ↑](#structure-of-this-tutorial)+ There are quite a few libraries that can be used as alternative preludes in Haskell, let's compare Relude with some of them. -### Relude vs Protolude [↑](#structure-of-this-tutorial)+### Relude vs Protolude +[[Back to the Table of Contents] ↑](#structure-of-this-tutorial)+ [Protolude](https://github.com/sdiehl/protolude) is one of the most popular alternative preludes. It's also relatively small, but: -1. Protolude supports older GHC versions (from GHC 7.6.1) while `relude` only+1. `relude` has custom HLint rules specific to it: you can use them to remove+   redundant imports or find hints on how to use functions from `relude`. Moreover,+   the HLint rules are generated using Dhall and there is [a blog post about+   this technique](https://kowainik.github.io/posts/2018-09-09-dhall-to-hlint).+   This allows to maintain HLint rules with less effort, even though it is+   already not an easy task.+2. One significant difference: `head` in `protolude` returns `Maybe a` while in+   `relude` it works with `NonEmpty`.+3. `relude` uses type-level features to provide better error messages+   on the difference from `Prelude`, and also to forbid `elem` and `notElem`+   functions for `Set` and `HashSet` (because `elem` from `Foldable` runs in+   _O(n)_ time and you can accidentally use `elem` from `Foldable` but with+   `relude` you can't).+4. Protolude supports older GHC versions (from GHC 7.6.1) while `relude` only    supports from GHC 8.0.2. So if you aim ancient GHC versions, `protolude`    might be a better choice. But because of that it contains a lot of CPP, code-   is ugly in some places as a consequence and it's more difficult to add,+   is scary in some places as a consequence and it is more difficult to add,    remove or change things there.-2. `relude` has much better documentation:+5. `relude` has much better documentation:     * [High-level overview of internal module structure](http://hackage.haskell.org/package/relude/docs/Relude.html)     * 100% Haddock coverage-    * Almost every function has usage examples and all examples are tested with-      `doctest` (which also sometimes hard to do because of multiple GHC+    * Every function has usage examples and all examples are tested with+      `doctest` (which also sometimes hard to do due to the multiple GHC       versions support, but we try really hard)     * [Tutorial + migration guide](#structure-of-this-tutorial) from       `Prelude` and just general description of the whole package and libraries       it depends on.-3. `relude` has custom HLint rules specific to it: you can use them to remove-   redundant imports or find hints how to use functions from `relude`. Moreover,-   the HLint rules are generated using Dhall and there is [a blog post about-   this technique](https://kowainik.github.io/posts/2018-09-09-dhall-to-hlint).-   This allows to maintain HLint rules much easier because it's already not an-   easy task.-4. `relude` has less dependencies and is slightly lighter because of that but still-   very powerful and useful.-5. One minor difference: `head` in `protolude` returns `Maybe a` while in-   `relude` it works with `NonEmpty`.-6. Minor feature: `relude` uses type-level magic to forbid `elem` and `notElem`-   functions for `Set` and `HashSet` (because `elem` from `Foldable` run in-   _O(n)_ time and you can accidentally use `elem` from `Foldable` but with-   `relude` you can't).+6. `relude` has less dependencies and is slightly lighter because of that but still+   is very powerful and useful. 7. `relude` is opt-in oriented and has a notion of `Extra.*` modules that are-   not exported by default from the `Relude` module. So we don't spoil global-   namespace but still have a lot of useful features like polymorphic functions-   to work with every `newtype`, `Enum/Bounded`-related useful utilities,-   functions to take a name of any type as `Text` and much more. It's very easy-   to make them accessible package-wide with `base-noprelude` trick!+   not exported by default from the `Relude` module. That means that we do not+   spoil the global namespace but still have a lot of useful features, like+   polymorphic functions to work with every `newtype`, `Enum/Bounded`-related+   useful utilities, functions to take a name of any type as `Text` and much+   more. It is a straightforward process to make them accessible package-wide+   with the `base-noprelude` trick! -## For Developers [↑](#structure-of-this-tutorial)+## For Developers +[[Back to the Table of Contents] ↑](#structure-of-this-tutorial)+ ### Generating .hlint.yaml  Note, that we are using custom `hlint` setting which are `Relude` specific. To@@ -519,11 +733,11 @@ First time:  ```shell-$ cabal new-install dhall-json+$ cabal v2-install dhall-json ``` -Dhall 9.0.0 is required, so make sure that the previous command installed-dhall-json >= 1.4.0.+Dhall 16.0.0 is required, so make sure that the previous command installed+`dhall-json` >= 1.6.4.  To generate `hlint` file: 
benchmark/Main.hs view
@@ -1,12 +1,4 @@-{--Copyright:  (c) 2016 Stephen Diehl-            (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>--}--module Main where+module Main (main) where  import Relude hiding (show) @@ -90,6 +82,7 @@     let testList   = [1..100000] :: [Int]     let flipFoldl' = flipfoldl' HashSet.insert mempty     let ghcFoldl'  = foldl' (\hash el -> HashSet.insert el hash) mempty-    bgroup "foldl'" [ bench "flipped" $ nf flipFoldl' testList-                    , bench "base"    $ nf ghcFoldl'  testList-                    ]+    bgroup "foldl'"+        [ bench "flipped" $ nf flipFoldl' testList+        , bench "base"    $ nf ghcFoldl'  testList+        ]
relude.cabal view
@@ -1,59 +1,85 @@ cabal-version:       2.4 name:                relude-version:             0.6.0.0-synopsis:            Custom prelude from Kowainik+version:             0.7.0.0+synopsis:            Safe, performant, user-friendly and lightweight Haskell Standard Library description:     @__relude__@ is an alternative prelude library. If you find the default     @Prelude@ unsatisfying, despite its advantages, consider using @relude@     instead.     .-    == Relude design goals+    == Relude goals and design principles+    * __Productivity.__ You can be more productive with a "non-standard" standard+      library, and @relude@ helps you with writing safer and more+      efficient code faster.     .-    * __Avoid all [partial functions](https://www.reddit.com/r/haskell/comments/5n51u3/why_are_partial_functions_as_in_head_tail_bad/)__-      (like @head :: [a] -> a@). The types of partial functions lie about their-      behavior and usage of such functions can lead to the unexpected bugs. Though-      you can still use some unsafe functions from @Relude.Unsafe@ module, but they-      are not exported by default.+    * __Total programming__. Usage of [/partial functions/](https://www.reddit.com/r/haskell/comments/5n51u3/why_are_partial_functions_as_in_head_tail_bad/)+      can lead to unexpected bugs and runtime exceptions in pure+      code. The types of partial functions lie about their behaviour. And+      even if it is not always possible to rely only on total functions,+      @relude@ strives to encourage best-practices and reduce the+      chances of introducing a bug.     .-    * __Type-safety__. We like to make invalid states unrepresantable. And if it's-      possible to express this concept through the types then we will do it.+        +---------------------------------+--------------------------------------------++        | __Partial__                     | __Total__                                  |+        +=================================+============================================++        | @head :: [a] -> a@              | @head :: NonEmpty a -> a@                  |+        +---------------------------------+--------------------------------------------++        | @tail :: [a] -> [a]@            | @tail :: NonEmpty a -> [a]@                |+        +---------------------------------+--------------------------------------------++        | @read :: Read a => String -> a@ | @readMaybe :: Read a => String -> Maybe a@ |+        +---------------------------------+--------------------------------------------++        | @fromJust :: Maybe a -> a@      | @fromMaybe :: a -> Maybe a -> a@           |+        +---------------------------------+--------------------------------------------++    .+    * __Type-safety__. We use the /"make invalid states unrepresentable"/ motto as one+      of our guiding principles. If it is possible, we express this concept through the+      types.       /Example:/ @ whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f () @     .-    * __Performance.__ Prefer @Text@ over @[String](https://www.reddit.com/r/haskell/comments/29jw0s/whats_wrong_with_string/)@,-      use spaceleak-free functions (like our custom @sum@ and @product@),+    * __Performance.__ We prefer @Text@ over @[String](https://www.reddit.com/r/haskell/comments/29jw0s/whats_wrong_with_string/)@,+      use space-leaks-free functions (e.g. our custom performant @sum@ and @product@),       introduce @\{\-\# INLINE \#\-\}@ and @\{\-\# SPECIALIZE \#\-\}@ pragmas where-      appropriate.+      appropriate, and make efficient container types+      (e.g. @Map@, @HashMap@, @Set@) more accesible.     .-    * __Minimalism__ (low number of dependencies). We don't force users of @relude@ to-      stick to some specific lens or text formatting or logging library. If-      possible, @relude@ tries to depend only on boot libraies.+    * __Minimalism__ (low number of dependencies). We don not force users of+      @relude@ to stick to any specific lens or text formatting or logging+      library. Where possible, @relude@ depends only on boot libraries.+      The [Dependency graph](https://raw.githubusercontent.com/kowainik/relude/master/relude-dependency-graph.png)+      of @relude@ can give you a clearer picture.     .-    * __Convenience__ (like lifted to @MonadIO@ functions, more reexports).-      Despite minimalism, we want to bring common types and functions (like-      @containers@ and @bytestring@) into scope because they are used in almost-      every application anyways.+    * __Convenience__. Despite minimalism, we want to bring commonly used+       types and functions into scope, and make available functions easier+       to use. Some examples of conveniences:     .-    * __Provide excellent documentation.__+       1. No need to import types like @NonEmpty@, @Text@, @Set@, @Reader[T]@, @MVar@, @STM@     .+       2. Functions like @liftIO@, @fromMaybe@, @sortWith@ are avaiable by default as well+    .+       3. @IO@ actions are lifted to @MonadIO@+    .+    * __Excellent documentation.__+    .         1. Tutorial     .         2. Migration guide from @Prelude@     .         3. Haddock for every function with examples tested by-           [doctest](http://hackage.haskell.org/package/doctest)).+           [doctest](http://hackage.haskell.org/package/doctest).     .         4. Documentation regarding [internal module structure](http://hackage.haskell.org/package/relude/docs/Relude.html)     .         5. @relude@-specific [HLint](http://hackage.haskell.org/package/hlint) rules: @[.hlint.yaml](https://github.com/kowainik/relude/blob/master/.hlint.yaml)@     .-    * __User-friendliness.__ Ability to quickly migrate to @relude@ if you're familiar-      with the common libraries like @text@ and @containers@. @relude@ also makes heavy usage-      of custom type errors to provide better UX.+    * __User-friendliness.__ Anyone should be able to quickly migrate to @relude@. Only+      some basic familiarity with the common libraries like @text@ and @containers@+      should be enough (but not necessary).     .-    * __Exploration.__ Experiment with new ideas and proposals without-      introducing breaking changes. @relude@ uses the approach with @Extra.*@-      modules which are not exported by default so it's quite easy to bring-      something new and let users decide to use it or not.+    * __Exploration.__ We have space to experiment with new ideas and proposals+      without introducing breaking changes. @relude@ uses the approach with+      @Extra.*@ modules which are not exported by default. The chosen approach makes it quite+      easy for us to provide new functionality without breaking anything and let+      the users decide to use it or not.  homepage:            https://github.com/kowainik/relude bug-reports:         https://github.com/kowainik/relude/issues@@ -61,18 +87,18 @@ license-file:        LICENSE author:              Dmitrii Kovanikov, Veronika Romashkina, Stephen Diehl, Serokell maintainer:          Kowainik <xrom.xkov@gmail.com>-copyright:           2016 Stephen Diehl, 2016-2018 Serokell, 2018-2019 Kowainik+copyright:           2016 Stephen Diehl, 2016-2018 Serokell, 2018-2020 Kowainik category:            Prelude stability:           stable build-type:          Simple extra-doc-files:     CHANGELOG.md-                     CONTRIBUTING.md                      README.md tested-with:         GHC == 8.0.2                      GHC == 8.2.2                      GHC == 8.4.4                      GHC == 8.6.5-                     GHC == 8.8.1+                     GHC == 8.8.3+                     GHC == 8.10.1   source-repository head@@ -80,7 +106,7 @@   location: git@github.com:kowainik/relude.git  common common-options-  build-depends:       base >= 4.9 && < 4.14+  build-depends:       base >= 4.9 && < 4.15    ghc-options:         -Wall                        -Wcompat@@ -88,9 +114,19 @@                        -Wincomplete-uni-patterns                        -Wincomplete-record-updates                        -fwarn-implicit-prelude+  if impl(ghc >= 8.0)+    ghc-options:       -Wredundant-constraints   if impl(ghc >= 8.2)     ghc-options:       -fhide-source-paths+  if impl(ghc >= 8.4)+    ghc-options:       -Wmissing-export-lists+                       -Wpartial-fields+  if impl(ghc >= 8.8)+    ghc-options:       -Wmissing-deriving-strategies+  if impl(ghc >= 8.10)+    ghc-options:       -Wunused-packages +   default-language:    Haskell2010   default-extensions:  InstanceSigs                        NoImplicitPrelude@@ -145,25 +181,26 @@                                Relude.String.Reexport                             -- not exported by default-                           Relude.Extra.Bifunctor-                           Relude.Extra.CallStack-                           Relude.Extra.Enum-                           Relude.Extra.Foldable-                           Relude.Extra.Foldable1-                           Relude.Extra.Group-                           Relude.Extra.Lens-                           Relude.Extra.Map-                           Relude.Extra.Newtype-                           Relude.Extra.Tuple-                           Relude.Extra.Type-                           Relude.Extra.Validation+                           Relude.Extra+                               Relude.Extra.Bifunctor+                               Relude.Extra.CallStack+                               Relude.Extra.Enum+                               Relude.Extra.Foldable+                               Relude.Extra.Foldable1+                               Relude.Extra.Group+                               Relude.Extra.Lens+                               Relude.Extra.Map+                               Relude.Extra.Newtype+                               Relude.Extra.Tuple+                               Relude.Extra.Type+                               Relude.Extra.Validation                            Relude.Unsafe     build-depends:       bytestring ^>= 0.10                      , containers >= 0.5.7 && < 0.7                      , deepseq ^>= 1.4-                     , ghc-prim >= 0.4.0.0 && < 0.6+                     , ghc-prim >= 0.4.0.0 && < 0.7                      , hashable >= 1.2 && < 1.4                      , mtl ^>= 2.2                      , stm >= 2.4 && < 2.6@@ -178,10 +215,13 @@   hs-source-dirs:      test   main-is:             Spec.hs -  other-modules:       Test.Relude.Property+  other-modules:       Test.Relude.Gen+                       Test.Relude.Container.One+                       Test.Relude.Property                        Test.Relude.Extra.Validation.Property   build-depends:       relude                      , bytestring+                     , containers                      , text                      , hedgehog ^>= 1.0 @@ -196,7 +236,6 @@   build-depends:       relude                      , doctest                      , Glob-                     , QuickCheck    ghc-options:         -threaded @@ -207,7 +246,6 @@   main-is:             Main.hs    build-depends:       relude-                     , containers                      , gauge                      , unordered-containers 
src/Relude.hs view
@@ -1,35 +1,58 @@-{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE Safe #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -The main module that reexports all functionality. It's considered to be a-@Prelude@ replacement.+@relude@ is a safe, performant, user-friendly and lightweight Haskell+standard library. -One of the most convenient ways to use @relude@ is via @mixins@ feature. To use-this feature need to specify @cabal-version: 2.4@ in your package description.-And then you can add the following lines to the required stanza to replace+"Relude" is the main module that reexports all functionality provided by the library that will replace the default @Prelude@ in your project.++== Usage++To start using @relude@ in your project, you can set the library up for you by+one of the following ways.++=== mixins++One of the most convenient ways to use @relude@ is via the @mixins@ feature. This+feature is available since @Cabal >= 2.2@. In order to use the @mixins@ feature+one needs to specify supported @cabal-version@ in your package description.+And then the following lines should be added to the required stanza to replace default "Prelude" with @relude@.  @-mixins: base hiding (Prelude)-      , relude (Relude as Prelude)+cabal-version: 2.4+...+library+  ...+  mixins: base hiding (Prelude)+        , relude (Relude as Prelude) @ +=== @base-noprelude@+ Alternatively, you can replace @base@ package in your dependencies with @[base-noprelude](http://hackage.haskell.org/package/base-noprelude)@ and add the following "Prelude" module to your package to use @relude@ by default in-every module instead of "Prelude":+every module instead of @base@ "Prelude":  @-__module__ Prelude (__module__ "Relude") __where__+__module__ Prelude+    ( __module__ "Relude"+    ) __where__+ __import__ "Relude" @ +=== @NoImplicitPrelude@+ If you want to use @relude@ per-module basis then just add next lines to your module to replace default "Prelude": @@ -39,86 +62,68 @@ __import__ "Relude" @ +== Structure+ This documentation section contains the description of internal module structure to help navigate between modules, search for interesting functionalities and understand where you need to put your new changes (if you're a contributor).  Functions and types are distributed across multiple modules and grouped by meaning or __category__. Name of the module should give you hints regarding what-this module contains. Some /categories/ contain a significant amount of both reexported+this module contains. Some /categories/ contain a significant amount of both+reexported functions and functions of our own. To make it easier to understand these enormous chunks of functions, all reexported stuff is moved into the separate module with name @Relude.SomeCategory.Reexport@ and our own functions and types are in @Relude.SomeCategory.SomeName@. For example, see modules "Relude.Foldable.Fold" and "Relude.Foldable.Reexport".--The following modules are not exported by default, but you can easily bring them to-every module in your package by modifying your "Prelude" file:--* __"Relude.Extra.Bifunctor"__: additional combinators for 'Bifunctor'.-* __"Relude.Extra.CallStack"__: useful functions to extract information from-  'CallStack'.-* __"Relude.Extra.Enum"__: extra utilities for types that implement 'Bounded'-  and 'Enum' constraints.-* __"Relude.Extra.Foldable"__: extra folds for instances of the 'Foldable'-  typeclass. Currently, just a short-circuitable left fold.-* __"Relude.Extra.Foldable1"__: 'Relude.Extra.Foldable1.Foldable1' typeclass-  like 'Foldable' but for non-empty structures.-* __"Relude.Extra.Group"__: grouping functions, polymorphic on return @Map@ type.-* __"Relude.Extra.Lens"__: minimal implementation of @lens@ package required-for basic usage.-* __"Relude.Extra.Map"__: typeclass for @Map@-like data structures.-* __"Relude.Extra.Newtype"__: generic functions that automatically work for any-  @newtype@.-* __"Relude.Extra.Tuple"__: functions for working with tuples.-* __"Relude.Extra.Type"__: functions for inspecting and working with types.-* __"Relude.Extra.Validation"__: 'Relude.Extra.Validation.Validation' data type.-* __"Relude.Unsafe"__: unsafe partial functions (produce 'error') for lists and-  'Maybe'. -}  module Relude-       ( -- * Modules available by default-         module Relude.Applicative-         -- $applicative-       , module Relude.Base-         -- $base-       , module Relude.Bool-         -- $bool-       , module Relude.Container-         -- $container-       , module Relude.Debug-         -- $debug-       , module Relude.DeepSeq-         -- $deepseq-       , module Relude.Exception-         -- $exception-       , module Relude.File-         -- $file-       , module Relude.Foldable-         -- $foldable-       , module Relude.Function-         -- $function-       , module Relude.Functor-         -- $functor-       , module Relude.Lifted-         -- $lifted-       , module Relude.List-         -- $list-       , module Relude.Monad-         -- $monad-       , module Relude.Monoid-         -- $monoid-       , module Relude.Nub-         -- $nub-       , module Relude.Numeric-         -- $numeric-       , module Relude.Print-         -- $print-       , module Relude.String-         -- $string-       ) where+    ( -- * Default Modules+      module Relude.Applicative+      -- $applicative+    , module Relude.Base+      -- $base+    , module Relude.Bool+      -- $bool+    , module Relude.Container+      -- $container+    , module Relude.Debug+      -- $debug+    , module Relude.DeepSeq+      -- $deepseq+    , module Relude.Exception+      -- $exception+    , module Relude.File+      -- $file+    , module Relude.Foldable+      -- $foldable+    , module Relude.Function+      -- $function+    , module Relude.Functor+      -- $functor+    , module Relude.Lifted+      -- $lifted+    , module Relude.List+      -- $list+    , module Relude.Monad+      -- $monad+    , module Relude.Monoid+      -- $monoid+    , module Relude.Nub+      -- $nub+    , module Relude.Numeric+      -- $numeric+    , module Relude.Print+      -- $print+    , module Relude.String+      -- $string +      -- * Extra Modules+      -- $extra+    ) where+ import Relude.Applicative import Relude.Base import Relude.Bool@@ -155,7 +160,7 @@  {- $container __"Relude.Container"__ provides 'One' typeclass for creating data structures-from singleton lement and reexports of types from packages @containers@ and+from singleton element and reexports of types from packages @containers@ and @unordered-containers@. -} @@ -206,7 +211,7 @@  {- $monad __"Relude.Monad"__ contains functions and data types from "Data.Maybe" and-"Data.Either" modules, monad transormers and other various combinators.+"Data.Either" modules, monad transformers and other various combinators. -}  {- $monoid@@ -229,4 +234,51 @@ {- $string __"Relude.String"__ contains reexports from @text@ and @bytestring@ packages with conversion functions between different textual types.+-}++{- $extra+The following modules are not exported by default, but you can easily bring them to+every module in your package by modifying your "Prelude" file:+++------------------------------+-----------------------------------------------------------++| __"Relude.Extra"__           | Reexports every @Relude.Extra.*@ module                   |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Bifunctor"__ | Additional combinators for 'Bifunctor'.                   |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.CallStack"__ | Useful functions to extract information from 'CallStack'. |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Enum"__      | Extra utilities for types that implement 'Bounded'        |+|                              | and 'Enum' constraints.                                   |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Foldable"__  | Extra folds for instances of the 'Foldable' typeclass.    |+|                              | Currently, just a short-circuitable left fold.            |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Foldable1"__ | 'Relude.Extra.Foldable1.Foldable1' typeclass              |+|                              | like 'Foldable' but for non-empty structures.             |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Group"__     | Grouping functions, polymorphic on return @Map@ type.     |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Lens"__      | Minimal implementation of @lens@ package required         |+|                              | for basic usage.                                          |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Map"__       | Typeclass for @Map@-like data structures.                 |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Newtype"__   | Generic functions that automatically work for any         |+|                              | @newtype@.                                                |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Tuple"__     | Functions for working with tuples.                        |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Type"__      | Functions for inspecting and working with types.          |++------------------------------+-----------------------------------------------------------++| __"Relude.Extra.Validation"__| 'Relude.Extra.Validation.Validation' data type.           |+|                              |                                                           |+|                              | __⚠️ Warning ⚠️__                                         |+|                              | "Relude.Extra.Validation" is deprecated in favour of      |+|                              | @validation-selective@:                                   |+|                              | <https://hackage.haskell.org/package/validation-selective>|++------------------------------+-----------------------------------------------------------++| __"Relude.Unsafe"__          | Unsafe partial functions (produce 'error') for lists and  |+|                              | 'Maybe'.                                                  |++------------------------------+-----------------------------------------------------------++ -}
src/Relude/Applicative.hs view
@@ -1,26 +1,42 @@+{-# LANGUAGE CPP  #-} {-# LANGUAGE Safe #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Convenient utils to work with 'Applicative'. There were more functions in this module-(see <https://www.stackage.org/haddock/lts-8.9/protolude-0.1.10/Applicative.html protolude version>)-but only convenient ans most used are left.+This module contains reexports of 'Applicative' and related functional.+Additionally, it provides convenient combinators to work with 'Applicative'. -}  module Relude.Applicative-       ( module Control.Applicative-       , pass-       , appliedTo-       ) where+    ( -- * Reexports+      -- $reexports+      Alternative (..)+    , Applicative (..)+    , Const (..)+    , ZipList (..)+#if __GLASGOW_HASKELL__ < 802+    , liftA2+#endif+    , liftA3+    , optional+    , (<**>) +      -- * Combinators+    , pass+    , appliedTo+    ) where+ import Control.Applicative (Alternative (..), Applicative (..), Const (..), ZipList (..), liftA2,                             liftA3, optional, (<**>)) + -- $setup -- >>> import Relude -- >>> import Relude.Monad (Maybe)@@ -43,28 +59,13 @@ Just 3 >>> Nothing & appliedTo (Just 2) Nothing++@since 0.5.0 -} appliedTo :: Applicative f => f a -> f (a -> b) -> f b appliedTo = (<**>) {-# INLINE appliedTo #-} --{--orAlt :: (Alternative f, Monoid a) => f a -> f a-orAlt f = f <|> pure mempty--orEmpty :: Alternative f => Bool -> a -> f a-orEmpty b a = if b then pure a else empty--eitherA :: Alternative f => f a -> f b -> f (Either a b)-eitherA a b = (Left <$> a) <|> (Right <$> b)--purer :: (Applicative f, Applicative g) => a -> f (g a)-purer = pure . pure--liftAA2 :: (Applicative f, Applicative g) => (a -> b -> c) -> f (g a) -> f (g b) -> f (g c)-liftAA2 = liftA2 . liftA2--(<<*>>) :: (Applicative f, Applicative g)  => f (g (a -> b)) -> f (g a) -> f (g b)-(<<*>>) = liftA2 (<*>)+{- $reexports+Main data types and functions reexported from "Control.Applicative". -}
src/Relude/Base.hs view
@@ -1,51 +1,54 @@-{-# LANGUAGE CPP    #-}-{-# LANGUAGE Unsafe #-}+{-# LANGUAGE CPP         #-}+{-# LANGUAGE Trustworthy #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Reexports from @Data.*@ and @GHC.*@ modules of-<https://www.stackage.org/lts-8.9/package/base-4.9.1.0 base> package.+<https://hackage.haskell.org/package/base base> package. -}  module Relude.Base-       ( -- * Base types-         module Data.Char+    ( -- * Base types+      module Data.Char -         -- * Base type classes-       , module Data.Eq-       , module Data.Ord+      -- * Base type classes+    , module Data.Eq+    , module Data.Ord -         -- * System IO-       , module System.IO+      -- * System IO+    , module System.IO -         -- * Types for type-level computation-       , module Data.Coerce-       , module Data.Kind-       , module Data.Proxy-       , module Data.Typeable-       , module Data.Void+      -- * Types for type-level computation+    , module Data.Coerce+    , module Data.Kind+    , module Data.Proxy+    , module Data.Typeable+    , module Data.Void -       , module GHC.Base-       , module GHC.Enum-       , module GHC.Generics-       , module GHC.Show+      -- * Basic type classes+    , module GHC.Base+    , module GHC.Enum+    , module GHC.Generics+    , module GHC.Show  -- * GHC-specific functionality #if MIN_VERSION_base(4,10,0)-       , module GHC.TypeNats+    , module GHC.TypeNats #else-       , module GHC.TypeLits+    , module GHC.TypeLits #endif -       , module GHC.OverloadedLabels-       , module GHC.ExecutionStack-       , module GHC.Stack-       ) where+    , module GHC.OverloadedLabels+    , module GHC.ExecutionStack+    , module GHC.Stack+    ) where  -- Base types import Data.Char (Char, chr)
src/Relude/Bool.hs view
@@ -3,18 +3,31 @@ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Convenient commonly used and very helpful functions to work with 'Bool' and also with monads. -}  module Relude.Bool-       ( module Relude.Bool.Guard-       , module Relude.Bool.Reexport-       ) where+    ( module Relude.Bool.Reexport+      -- $reexport+    , module Relude.Bool.Guard+      -- $guard+    ) where  import Relude.Bool.Guard import Relude.Bool.Reexport++{- $reexport+Reexports from "Data.Bool" and "Control.Monad". Includes necessary types and+functions to work with 'Bool' type.+-}++{- $guard+Boolean combinators that work in monads. Like 'ifM' or 'guardM'.+-}
src/Relude/Bool/Guard.hs view
@@ -1,28 +1,33 @@+{-# LANGUAGE Safe #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Monadic boolean combinators. -}  module Relude.Bool.Guard-       ( guarded-       , guardM-       , ifM-       , unlessM-       , whenM-       , (&&^)-       , (||^)-       ) where+    ( guarded+    , guardM+    , ifM+    , unlessM+    , whenM+    , (&&^)+    , (||^)+    ) where  import Relude.Applicative (Alternative, Applicative (..), empty) import Relude.Bool.Reexport (Bool (..), guard, unless, when) import Relude.Function (flip) import Relude.Monad (Monad, MonadPlus, (>>=)) + -- $setup -- >>> import Relude.Applicative (pure) -- >>> import Relude.Bool.Reexport (Bool (..))@@ -32,50 +37,54 @@ -- >>> import Relude.Print (putTextLn) -- >>> import Relude (Int, String, even, const) --- | Monadic version of 'when'.------ >>> whenM (pure False) $ putTextLn "No text :("--- >>> whenM (pure True)  $ putTextLn "Yes text :)"--- Yes text :)--- >>> whenM (Just True) (pure ())--- Just ()--- >>> whenM (Just False) (pure ())--- Just ()--- >>> whenM Nothing (pure ())--- Nothing+{- | Monadic version of 'when'.++>>> whenM (pure False) $ putTextLn "No text :("+>>> whenM (pure True)  $ putTextLn "Yes text :)"+Yes text :)+>>> whenM (Just True) (pure ())+Just ()+>>> whenM (Just False) (pure ())+Just ()+>>> whenM Nothing (pure ())+Nothing+-} whenM :: Monad m => m Bool -> m () -> m () whenM p m = p >>= flip when m {-# INLINE whenM #-} --- | Monadic version of 'unless'.------ >>> unlessM (pure False) $ putTextLn "No text :("--- No text :(--- >>> unlessM (pure True) $ putTextLn "Yes text :)"+{- | Monadic version of 'unless'.++>>> unlessM (pure False) $ putTextLn "No text :("+No text :(+>>> unlessM (pure True) $ putTextLn "Yes text :)"+-} unlessM :: Monad m => m Bool -> m () -> m () unlessM p m = p >>= flip unless m {-# INLINE unlessM #-} --- | Monadic version of @if-then-else@.------ >>> ifM (pure True) (putTextLn "True text") (putTextLn "False text")--- True text+{- | Monadic version of @if-then-else@.++>>> ifM (pure True) (putTextLn "True text") (putTextLn "False text")+True text+-} ifM :: Monad m => m Bool -> m a -> m a -> m a ifM p x y = p >>= \b -> if b then x else y {-# INLINE ifM #-} --- | Monadic version of 'guard'. Occasionally useful.--- Here some complex but real-life example:------ @--- findSomePath :: IO (Maybe FilePath)------ somePath :: MaybeT IO FilePath--- somePath = do---     path <- MaybeT findSomePath---     guardM $ liftIO $ doesDirectoryExist path---     return path--- @+{- | Monadic version of 'guard'. Occasionally useful.+Here some complex but real-life example:++@+findSomePath :: IO (Maybe FilePath)++somePath :: MaybeT IO FilePath+somePath = do+    path <- MaybeT findSomePath+    guardM $ liftIO $ doesDirectoryExist path+    return path+@+-} guardM :: MonadPlus m => m Bool -> m () guardM f = f >>= guard {-# INLINE guardM #-}@@ -109,18 +118,40 @@ guarded p a = if p a then pure a else empty {-# INLINE guarded #-} --- | Monadic version of 'Data.Bool.(&&)' operator.------ >>> Just False &&^ error "Shouldn't be evaluated"--- Just False+{- | Monadic version of 'Data.Bool.(&&)' operator.++>>> Just False &&^ Just True+Just False+>>> Just True &&^ Just True+Just True+>>> Just True &&^ Nothing+Nothing+>>> Just False &&^ Nothing+Just False+>>> Just False &&^ error "Shouldn't be evaluated"+Just False++@since 0.4.0+-} (&&^) :: Monad m => m Bool -> m Bool -> m Bool (&&^) e1 e2 = ifM e1 e2 (pure False) {-# INLINE (&&^) #-} --- | Monadic version of 'Data.Bool.(||)' operator.------ >>> Just True ||^ error "Shouldn't be evaluated"--- Just True+{- | Monadic version of 'Data.Bool.(||)' operator.++>>> Just False ||^ Just True+Just True+>>> Just False ||^ Just False+Just False+>>> Just False ||^ Nothing+Nothing+>>> Just True ||^ Nothing+Just True+>>> Just True ||^ error "Shouldn't be evaluated"+Just True++@since 0.4.0+-} (||^) :: Monad m => m Bool -> m Bool -> m Bool e1 ||^ e2 = ifM e1 (pure True) e2 {-# INLINE (||^) #-}
src/Relude/Bool/Reexport.hs view
@@ -1,17 +1,30 @@+{-# LANGUAGE Safe #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Reexports functions to work with 'Bool' type. -}  module Relude.Bool.Reexport-       ( module Control.Monad-       , module Data.Bool-       ) where+    ( -- * "Data.Bool" reexports+      Bool (..)+    , bool+    , not+    , otherwise+    , (&&)+    , (||)+      -- * "Control.Monad" reexports+    , guard+    , when+    , unless+    ) where  import Control.Monad (guard, unless, when) import Data.Bool (Bool (..), bool, not, otherwise, (&&), (||))
src/Relude/Container.hs view
@@ -1,17 +1,38 @@+{-# LANGUAGE Safe #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  This module exports all container-related stuff. -}  module Relude.Container-       ( module Relude.Container.One-       , module Relude.Container.Reexport-       ) where+    ( module Relude.Container.One+      -- $one+    , module Relude.Container.Reexport+      -- $reexport+    ) where  import Relude.Container.One import Relude.Container.Reexport++{- $one+'One' is a typeclass for creating structures from a singleton element.+This module provides many useful instances of 'One' for common containers+as well.+-}++{- $reexport+Reexports container-related functions, typeclasses and data types from+the following packages:++* [@base@](https://hackage.haskell.org/package/base)+* [@containers@](https://hackage.haskell.org/package/containers)+* [@unordered-containers@](https://hackage.haskell.org/package/unordered-containers)+-}
src/Relude/Container/One.hs view
@@ -1,24 +1,30 @@ {-# LANGUAGE FlexibleContexts  #-} {-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE Safe              #-} {-# LANGUAGE TypeFamilies      #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Typeclass for creating structures from a singleton element. It has three main goals:+'One' is a typeclass for creating structures from a singleton element.+It has three main goals:  1. Give a shorter name for the construction: uses 'one' instead of common @singleton@. 2. Work with monomorphic structures like 'T.Text' or 'IntSet'. 3. Give a clearer and less scary name for cases where you can use 'Relude.pure' or @(:[])@.++@since 0.1.0 -}  module Relude.Container.One-       ( One (..)-       ) where+    ( One (..)+    ) where  import Relude.Base (Char) import Relude.Container.Reexport (HashMap, HashSet, Hashable, IntMap, IntSet, Map, Set, uncurry)@@ -44,13 +50,6 @@  -- $setup -- >>> import Relude--- >>> import qualified Data.IntSet as IntSet--- >>> import qualified Data.HashMap.Strict as HashMap--- >>> import qualified Data.Text as Text--- >>> import qualified Data.ByteString as ByteString--- >>> import qualified Data.ByteString.Short as ShortByteString--- >>> import qualified Data.Text.Lazy as LText--- >>> import qualified Data.ByteString.Lazy as LByteString  {- | Typeclass for data types that can be created from one element. @@ -83,7 +82,9 @@ >>> one 42 :: [Int] [42] -prop> length (one @[Int] x) == 1+@+law> 'Relude.length' ('one' @[a] x) ≡ 1+@ -} instance One [a] where     type OneItem [a] = a@@ -98,7 +99,9 @@ >>> one 42 :: NonEmpty Int 42 :| [] -prop> length (one @(NonEmpty Int) x) == 1+@+law> 'Relude.length' ('one' @('NE.NonEmpty' a) x) ≡ 1+@ -} instance One (NE.NonEmpty a) where     type OneItem (NE.NonEmpty a) = a@@ -112,7 +115,9 @@ >>> one 42 :: Seq Int fromList [42] -prop> length (one @(Seq Int) x) == 1+@+law> 'Relude.length' ('one' @('SEQ.Seq' a) x) ≡ 1+@ -} instance One (SEQ.Seq a) where     type OneItem (SEQ.Seq a) = a@@ -128,7 +133,9 @@ >>> one 'a' :: Text "a" -prop> Text.length (one x) == 1+@+law> 'Data.Text.length' ('one' x) ≡ 1+@ -} instance One T.Text where     type OneItem T.Text = Char@@ -142,7 +149,9 @@ >>> one 'a' :: LText "a" -prop> LText.length (one x) == 1+@+law> 'Data.Text.Lazy.length' ('one' x) ≡ 1+@ -} instance One TL.Text where     type OneItem TL.Text = Char@@ -156,7 +165,9 @@ >>> one 97 :: ByteString "a" -prop> ByteString.length (one x) == 1+@+law> 'BS.length' ('one' x) ≡ 1+@ -} instance One BS.ByteString where     type OneItem BS.ByteString = Word8@@ -170,7 +181,9 @@ >>> one 97 :: LByteString "a" -prop> LByteString.length (one x) == 1+@+law> 'BSL.length' ('one' x) ≡ 1+@ -} instance One BSL.ByteString where     type OneItem BSL.ByteString = Word8@@ -184,7 +197,9 @@ >>> one 97 :: ShortByteString "a" -prop> ShortByteString.length (one x) == 1+@+law> 'SBS.length' ('one' x) ≡ 1+@ -} instance One SBS.ShortByteString where     type OneItem SBS.ShortByteString = Word8@@ -200,7 +215,9 @@ >>> one (3, "foo") :: Map Int Text fromList [(3,"foo")] -prop> length (one @(Map Int String) x) == 1+@+law> 'Relude.length' ('one' @('Map' k v) (k, v)) ≡ 1+@ -} instance One (Map k v) where     type OneItem (Map k v) = (k, v)@@ -214,7 +231,9 @@ >>> one (3, "foo") :: HashMap Int Text fromList [(3,"foo")] -prop> length (one @(HashMap Int String) x) == 1+@+law> 'Relude.length' ('one' @('HashMap' k v) (k, v)) ≡ 1+@ -} instance Hashable k => One (HashMap k v) where     type OneItem (HashMap k v) = (k, v)@@ -228,7 +247,9 @@ >>> one (3, "foo") :: IntMap Text fromList [(3,"foo")] -prop> length (one @(IntMap String) x) == 1+@+law> 'Relude.length' ('one' @('IntMap' a) x) ≡ 1+@ -} instance One (IntMap v) where     type OneItem (IntMap v) = (Int, v)@@ -244,7 +265,9 @@ >>> one 42 :: Set Int fromList [42] -prop> length (one @(Set Int) x) == 1+@+law> 'Relude.length' ('one' @('Set' a) x) ≡ 1+@ -} instance One (Set a) where     type OneItem (Set a) = a@@ -258,7 +281,9 @@ >>> one 42 :: HashSet Int fromList [42] -prop> length (one @(HashSet Int) x) == 1+@+law> 'Relude.length' ('one' @('HashSet' a) x) ≡ 1+@ -} instance Hashable a => One (HashSet a) where     type OneItem (HashSet a) = a@@ -272,7 +297,9 @@ >>> one 42 :: IntSet fromList [42] -prop> IntSet.size (one x) == 1+@+law> 'Data.IntSet.size' ('one' x) ≡ 1+@ -} instance One IntSet where     type OneItem IntSet = Int
src/Relude/Container/Reexport.hs view
@@ -1,26 +1,44 @@+{-# LANGUAGE Trustworthy #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Reexports all container-related stuff from @base@, @containers@ and-@unordered-containers@ packages.+Reexports container-related data types, functions and typeclasses from @base@,+@containers@ and @unordered-containers@ packages. -}  module Relude.Container.Reexport-       ( module Data.Hashable-       , module Data.HashMap.Strict-       , module Data.HashSet-       , module Data.IntMap.Strict-       , module Data.IntSet-       , module Data.Map.Strict-       , module Data.Sequence-       , module Data.Set-       , module Data.Tuple-       , module GHC.Exts-       ) where+    ( -- * "Data.Hashable" reexports+      Hashable (..)+      -- * "Data.HashMap.Strict" reexports+    , HashMap+      -- * "Data.HashSet" reexports+    , HashSet+      -- * "Data.IntMap.Strict" reexports+    , IntMap+      -- * "Data.IntSet" reexports+    , IntSet+      -- * "Data.Map.Strict" reexports+    , Map+      -- * "Data.Sequence" reexports+    , Seq+      -- * "Data.Set" reexports+    , Set+      -- * "Data.Tuple" reexports+    , curry+    , fst+    , snd+    , swap+    , uncurry+      -- * "GHC.Exts" reexports+    , IsList (..)+    ) where  import Data.Hashable (Hashable (hashWithSalt)) import Data.HashMap.Strict (HashMap)
src/Relude/Debug.hs view
@@ -12,35 +12,49 @@ {-# LANGUAGE TypeOperators        #-} {-# LANGUAGE UndecidableInstances #-} +#if __GLASGOW_HASKELL__ > 802+{-# LANGUAGE DerivingStrategies   #-}+#endif+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Functions for debugging. If you left these functions in your code then a warning-is generated to remind you about left usages. Also some functions (and data-types) are convenient for prototyping.+Functions for debugging and prototyping. If you leave these functions in your+code then a warning is generated to remind you about left usages. -Use these functions only for debugging purposes. They break referential trasparency,-they are only useful when you want to observe intermediate values of your pure functions.+@+__ghci>__ foo = trace "I forgot trace in code"++\<interactive\>:4:7: __warning__: [-Wdeprecations]+    In the use of ‘trace’ (imported from "Relude"):+    "'trace' remains in code"+@++__⚠ NOTE:__ Use these functions only for debugging purposes. They break referential+transparency, they are only useful when you want to observe intermediate values+of your pure functions. -}  module Relude.Debug-       ( -- * Tracing-         trace-       , traceM-       , traceId-       , traceShow-       , traceShowId-       , traceShowM+    ( -- * Tracing+      trace+    , traceM+    , traceId+    , traceShow+    , traceShowId+    , traceShowM -         -- * Imprecise error-       , error-       , Undefined (..)-       , undefined-       ) where+      -- * Imprecise error+    , error+    , Undefined (..)+    , undefined+    ) where  import Data.Data (Data) import GHC.Exts (RuntimeRep, TYPE)@@ -170,13 +184,13 @@ >>> error "oops" *** Exception: oops CallStack (from HasCallStack):-  error, called at src\\Relude\\Debug.hs:204:11 in ...+  error, called at src\\Relude\\Debug.hs:218:11 in ...   ... #else >>> error "oops" *** Exception: oops CallStack (from HasCallStack):-  error, called at src/Relude/Debug.hs:204:11 in ...+  error, called at src/Relude/Debug.hs:218:11 in ... ... #endif @@ -224,7 +238,11 @@  -- | Similar to 'undefined' but data type. data Undefined = Undefined+#if __GLASGOW_HASKELL__ > 802+    deriving stock (Eq, Ord, Show, Read, Enum, Bounded, Data, Typeable, Generic)+#else     deriving (Eq, Ord, Show, Read, Enum, Bounded, Data, Typeable, Generic)+#endif {-# WARNING Undefined "'Undefined' type remains in code" #-}  -- | 'Prelude.undefined' that leaves warning in code on every usage.
src/Relude/DeepSeq.hs view
@@ -1,23 +1,33 @@+{-# LANGUAGE Safe #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  This module contains useful functions to evaluate expressions to weak-head-normal form or just normal form. Useful to force traces or @error@ inside-monadic computation or to remove space leaks.+normal form (WHNF) or just normal form (NF). Useful to force traces or @error@s+inside monadic computations or to remove space leaks. -}  module Relude.DeepSeq-       ( module Control.DeepSeq-       , evaluateNF-       , evaluateNF_-       , evaluateWHNF-       , evaluateWHNF_-       ) where+    ( -- * "Control.DeepSeq" reexports+      NFData (..)+    , deepseq+    , force+    , ($!!) +      -- * Evaluation+    , evaluateNF+    , evaluateNF_+    , evaluateWHNF+    , evaluateWHNF_+    ) where+ import Control.DeepSeq (NFData (..), deepseq, force, ($!!))  import Relude.Base (IO, seq)@@ -32,12 +42,12 @@  {- | Lifted alias for 'Control.Exception.Base.evaluate' with clearer name. ->>> list = [2, 1, 3] :: [Int]+>>> let list = [1..5] :: [Int] >>> :sprint list list = _ >>> () <$ evaluateWHNF list >>> :sprint list-list = _ : _+list = 1 : _ -} evaluateWHNF :: MonadIO m => a -> m a evaluateWHNF = liftIO . Control.Exception.Base.evaluate@@ -46,13 +56,12 @@  {- | Like 'evaluateWHNF' but discards value. ->>> list = [2, 1, 3] :: [Int]+>>> let list = [1..5] :: [Int] >>> :sprint list list = _ >>> evaluateWHNF_ list >>> :sprint list-list = _ : _-+list = 1 : _ -} evaluateWHNF_ :: MonadIO m => a -> m () evaluateWHNF_ what = (`seq` ()) <$!> evaluateWHNF what@@ -61,13 +70,12 @@  {- | Alias for @evaluateWHNF . force@ with clearer name. ->>> list = [2, 1, 3] :: [Int]+>>> let list = [1..5] :: [Int] >>> :sprint list list = _ >>> () <$ evaluateNF list >>> :sprint list-list = [2,1,3]-+list = [1,2,3,4,5] -} evaluateNF :: (NFData a, MonadIO m) => a -> m a evaluateNF = evaluateWHNF . force@@ -77,13 +85,12 @@ {- | Alias for @evaluateWHNF . rnf@. Similar to 'evaluateNF' -- but discards resulting value. ->>> list = [2, 1, 3] :: [Int]+>>> let list = [1..5] :: [Int] >>> :sprint list list = _ >>> evaluateNF_ list >>> :sprint list-list = [2,1,3]-+list = [1,2,3,4,5] -} evaluateNF_ :: (NFData a, MonadIO m) => a -> m () evaluateNF_ = evaluateWHNF . rnf
src/Relude/Exception.hs view
@@ -1,26 +1,36 @@+{-# LANGUAGE CPP                   #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PatternSynonyms       #-} {-# LANGUAGE Safe                  #-} {-# LANGUAGE ViewPatterns          #-} +#if __GLASGOW_HASKELL__ > 802+{-# LANGUAGE DerivingStrategies    #-}+#endif+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Re-exports most useful functionality from the "Control.Exception" module. Also provides some convenient utilities to throw and handle exceptions. -}  module Relude.Exception-       ( module Control.Exception+    ( -- * "Control.Exception" reexports+      Exception (..)+    , SomeException (..) -       , Bug (..)-       , bug-       , pattern Exc-       ) where+      -- * 'Bug's+    , Bug (..)+    , bug+    , pattern Exc+    ) where  import Control.Exception (Exception (..), SomeException (..)) import Data.List ((++))@@ -37,7 +47,11 @@ not meant to be ever executed, but happens to be executed anyway. -} data Bug = Bug SomeException CallStack+#if __GLASGOW_HASKELL__ > 802+    deriving stock (Show)+#else     deriving (Show)+#endif  instance Exception Bug where     displayException (Bug e cStack) = E.displayException e ++ "\n"@@ -47,12 +61,13 @@ impureThrow :: Exception e => e -> a impureThrow = E.throw . E.toException --- | Generate a pure value which, when forced, will synchronously--- throw the exception wrapped into 'Bug' data type.+{- | Generate a pure value which, when forced, will synchronously+throw the exception wrapped into 'Bug' data type.+-} bug :: (HasCallStack, Exception e) => e -> a bug e = impureThrow (Bug (E.toException e) callStack) -{- | Pattern synonym to easy pattern matching on exceptions. So intead of+{- | Pattern synonym to easy pattern matching on exceptions. So instead of writing something like this:  @
+ src/Relude/Extra.hs view
@@ -0,0 +1,107 @@+{- |+Copyright:  (c) 2019-2020 Kowainik+SPDX-License-Identifier: MIT+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable++This module exports all extra-related stuff.+The extra modules are not exported by default, but you can easily bring them to+every module in your package by modifying your "Prelude" file.+-}++module Relude.Extra+    ( module Relude.Extra.Bifunctor+      -- $Bifunctor+    , module Relude.Extra.CallStack+      -- $CallStack+    , module Relude.Extra.Enum+      -- $Enum+    , module Relude.Extra.Foldable+      -- $Foldable+    , module Relude.Extra.Foldable1+      -- $Foldable1+    , module Relude.Extra.Group+      -- $Group+    , module Relude.Extra.Lens+      -- $Lens+    , module Relude.Extra.Map+      -- $Map+    , module Relude.Extra.Newtype+      -- $Newtype+    , module Relude.Extra.Tuple+      -- $Tuple+    , module Relude.Extra.Type+      -- $Type+    , module Relude.Extra.Validation+      -- $Validation+    ) where++import Relude.Extra.Bifunctor+import Relude.Extra.CallStack+import Relude.Extra.Enum+import Relude.Extra.Foldable+import Relude.Extra.Foldable1+import Relude.Extra.Group+import Relude.Extra.Lens+import Relude.Extra.Map+import Relude.Extra.Newtype+import Relude.Extra.Tuple+import Relude.Extra.Type+import Relude.Extra.Validation++{- $Bifunctor+Additional combinators for 'Relude.Bifunctor'.+-}++{- $CallStack+Useful functions to extract information from 'Relude.CallStack'.+-}+{- $Enum+Extra utilities for types that implement 'Relude.Bounded' and 'Relude.Enum'+constraints.+-}+{- $Foldable+Extra folds for instances of the 'Relude.Foldable' typeclass.+Currently, just a short-circuitable left fold 'foldlSC'.+-}++{- $Foldable1+'Foldable1' is a typeclass like 'Relude.Foldable' but for non-empty structures.+For example, 'Relude.NonEmpty', 'Relude.Identity'.++'Foldable1' has all type-safe and total methods like `head1`, `maximum1` in+contradiction with 'Data.Foldable.Foldable'.+-}++{- $Group+Grouping functions, polymorphic on return @Map@ type.+-}++{- $Lens+Minimal implementation of @lens@ package required for basic usage.+-}++{- $Map+The typeclass for @Map@-like data structures.+-}++{- $Newtype+Generic functions that automatically work for any @newtype@.+-}++{- $Tuple+Functions for working with tuples.+-}++{- $Type+Functions for inspecting and working with types.+-}++{- $Validation+'Validation' data type.++__⚠️ Warning ⚠️__+"Relude.Extra.Validation" is deprecated in favour+of [validation-selective](https://hackage.haskell.org/package/validation-selective).+-}
src/Relude/Extra/Bifunctor.hs view
@@ -1,7 +1,11 @@+{-# LANGUAGE Safe #-}+ {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable  Useful combinators for bifunctors inside functors. This set of functions is useful when you want to work with types like these ones:@@ -16,20 +20,22 @@ doo :: (a, a) dee :: Either a a @++@since 0.1.0 -}  module Relude.Extra.Bifunctor-       ( bimapBoth-       , bimapF-       , firstF-       , secondF-       ) where+    ( bimapBoth+    , bimapF+    , firstF+    , secondF+    ) where  import Relude  {- | Maps a function over both elements of a bifunctor. ->>> bimapBoth length ("a", "bb")+>>> bimapBoth length ([True], [False, True]) (1,2) >>> map (bimapBoth not) [Left True, Right False] [Left False,Right True]@@ -44,6 +50,8 @@  >>> bimapF not length $ Just (False, ['a', 'b']) Just (True,2)++@since 0.1.0 -} bimapF  :: (Functor f, Bifunctor p) => (a -> c) -> (b -> d) -> f (p a b) -> f (p c d) bimapF f g = fmap (bimap f g)@@ -53,6 +61,8 @@  >>> firstF not $ Just (False, ['a', 'b']) Just (True,"ab")++@since 0.1.0 -} firstF  :: (Functor f, Bifunctor p) => (a -> c) -> f (p a b) -> f (p c b) firstF = fmap . first@@ -62,6 +72,8 @@  >>> secondF length  $ Just (False, ['a', 'b']) Just (False,2)++@since 0.1.0 -} secondF  :: (Functor f, Bifunctor p) => (b -> d) -> f (p a b) -> f (p a d) secondF = fmap . second
src/Relude/Extra/CallStack.hs view
@@ -1,15 +1,21 @@+{-# LANGUAGE Safe #-}+ {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable  Contains useful functions to work with GHC callstack.++@since 0.2.0 -}  module Relude.Extra.CallStack-       ( ownName-       , callerName-       ) where+    ( ownName+    , callerName+    ) where  import Relude @@ -23,6 +29,8 @@ >>> bar :: HasCallStack => String; bar = foo >>> bar "foo"++@since 0.2.0 -} ownName :: HasCallStack => String ownName = case getCallStack callStack of@@ -31,7 +39,7 @@  {- | This function returns the name of its caller of the caller function, but it requires that the caller function and caller of the caller function have-'HasCallStack' constraint. Otherwise, it returns @"<unkown>"@. It's useful for+'HasCallStack' constraint. Otherwise, it returns @"<unknown>"@. It's useful for logging:  >>> log :: HasCallStack => String -> IO (); log s = putStrLn $ callerName ++ ":" ++ s@@ -40,6 +48,8 @@ greeting:Starting... Hello! greeting:Ending...++@since 0.2.0 -} callerName :: HasCallStack => String callerName = case getCallStack callStack of
src/Relude/Extra/Enum.hs view
@@ -1,38 +1,78 @@+{-# LANGUAGE Safe #-}+ {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable  Mini @bounded-enum@ framework inside @relude@.++@since 0.1.0 -}  module Relude.Extra.Enum-       ( universe-       , inverseMap-       , next-       , prev-       , prec-       , safeToEnum-       ) where+    ( universe+    , universeNonEmpty+    , inverseMap+    , next+    , prev+    , safeToEnum+    ) where  import Relude-import Relude.Extra.Tuple (mapToFst)+import Relude.Extra.Tuple (fmapToFst)  import qualified Data.Map.Strict as M   {- | Returns all values of some 'Bounded' 'Enum' in ascending order. +>>> universe :: [Bool]+[False,True]++>>> universe @Ordering+[LT,EQ,GT]+ >>> data TrafficLight = Red | Blue | Green deriving (Show, Enum, Bounded) >>> universe :: [TrafficLight] [Red,Blue,Green]->>> universe :: [Bool]-[False,True]++>>> data Singleton = Singleton deriving (Show, Enum, Bounded)+>>> universe @Singleton+[Singleton]++@since 0.1.0 -} universe :: (Bounded a, Enum a) => [a] universe = [minBound .. maxBound] {-# INLINE universe #-} +{- | Like 'universe', but returns 'NonEmpty' list of some enumeration++>>> universeNonEmpty :: NonEmpty Bool+False :| [True]++>>> universeNonEmpty @Ordering+LT :| [EQ,GT]++>>> data TrafficLight = Red | Blue | Green deriving (Show, Eq, Enum, Bounded)+>>> universeNonEmpty :: NonEmpty TrafficLight+Red :| [Blue,Green]++>>> data Singleton = Singleton deriving (Show, Eq, Enum, Bounded)+>>> universeNonEmpty @Singleton+Singleton :| []++@since 0.7.0.0+-}+universeNonEmpty :: forall a . (Bounded a, Enum a, Eq a) => NonEmpty a+universeNonEmpty+    | minBound @a == maxBound = minBound :| []+    | otherwise = minBound :| [succ minBound .. maxBound]+{-# INLINE universeNonEmpty #-}+ {- | @inverseMap f@ creates a function that is the inverse of a given function @f@. It does so by constructing 'M.Map' internally for each value @f a@. The implementation makes sure that the 'M.Map' is constructed only once and then@@ -81,6 +121,8 @@ parseGhcVer :: 'Text' -> 'Maybe' GhcVer parseGhcVer = 'inverseMap' showGhcVer @++@since 0.1.1 -} inverseMap     :: forall a k .@@ -90,7 +132,7 @@ inverseMap f = \k -> M.lookup k dict   where     dict :: M.Map k a-    dict = M.fromList $ map (mapToFst f) (universe @a)+    dict = M.fromList $ fmapToFst f (universe @a) {-# INLINE inverseMap #-}  {- | Like 'succ', but doesn't fail on 'maxBound'. Instead it returns 'minBound'.@@ -101,6 +143,8 @@ False >>> succ True *** Exception: Prelude.Enum.Bool.succ: bad argument++@since 0.1.0 -} next :: (Eq a, Bounded a, Enum a) => a -> a next e@@ -125,11 +169,6 @@     | otherwise     = pred e {-# INLINE prev #-} --- | See 'prev'.-prec :: (Eq a, Bounded a, Enum a) => a -> a-prec = prev-{-# DEPRECATED prec "Use 'prev' instead, it has more idiomatic and common name" #-}- {- | Returns 'Nothing' if given 'Int' outside range.  >>> safeToEnum @Bool 0@@ -140,6 +179,8 @@ Nothing >>> safeToEnum @Bool (-1) Nothing++@since 0.1.0 -} safeToEnum :: forall a . (Bounded a, Enum a) => Int -> Maybe a safeToEnum i = guard (fromEnum @a minBound <= i && i <= fromEnum @a maxBound) $> toEnum i
src/Relude/Extra/Foldable.hs view
@@ -1,7 +1,11 @@+{-# LANGUAGE Safe #-}+ {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable  Contains utility functions for working with tuples. @@ -9,8 +13,8 @@ -}  module Relude.Extra.Foldable-       ( foldlSC-       ) where+    ( foldlSC+    ) where  import Relude 
src/Relude/Extra/Foldable1.hs view
@@ -1,19 +1,32 @@+{-# OPTIONS_GHC -Wno-redundant-constraints #-}+ {-# LANGUAGE DataKinds            #-}+{-# LANGUAGE Safe                 #-} {-# LANGUAGE TypeFamilies         #-} {-# LANGUAGE TypeOperators        #-} {-# LANGUAGE UndecidableInstances #-}  {- | Copyright:  (c) 2011-2015 Edward Kmett-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable++'Foldable1' is a typeclass like 'Data.Foldable.Foldable' but for non-empty+structures. For example, 'Relude.NonEmpty', 'Relude.Identity'.++'Foldable1' has all type-safe and total methods like `head1`, `maximum1` in+contradiction with 'Data.Foldable.Foldable'.++@since 0.3.0 -}  module Relude.Extra.Foldable1-       ( Foldable1 (..)-       , foldl1'-       ) where+    ( Foldable1 (..)+    , foldl1'+    ) where  import Relude hiding (Product (..), Sum (..)) import Relude.Extra.Newtype (( #. ))@@ -29,6 +42,8 @@ -- >>> import Relude  {- | The class of foldable data structures that cannot be empty.++@since 0.3.0 -} class Foldable f => Foldable1 f where     {-# MINIMAL foldMap1 #-}@@ -52,7 +67,7 @@     fold1 :: Semigroup m => f m -> m     fold1 = foldMap1 id -    {- | Convert a non-empty data structre to a NonEmpty list.+    {- | Convert a non-empty data structure to a NonEmpty list.      >>> toNonEmpty (Identity 2)     2 :| []@@ -84,7 +99,7 @@     maximum1 :: Ord a => f a -> a     maximum1 = SG.getMax #. foldMap1 SG.Max -    {- | The smallest elemenet of a non-empty data structure.+    {- | The smallest element of a non-empty data structure.      >>> minimum1 (32 :| [64, 8, 128, 16])     8@@ -92,6 +107,10 @@     minimum1 :: Ord a => f a -> a     minimum1 = SG.getMin #. foldMap1 SG.Min +{- |++@since 0.3.0+-} instance Foldable1 NonEmpty where     fold1 :: Semigroup m => NonEmpty m -> m     fold1 = sconcat@@ -120,6 +139,10 @@     {-# INLINE maximum1 #-}     {-# INLINE minimum1 #-} +{- |++@since 0.3.0+-} instance Foldable1 Identity where     foldMap1 :: Semigroup m => (a -> m) -> Identity a -> m     foldMap1 = coerce@@ -149,6 +172,10 @@     minimum1 = coerce     {-# INLINE minimum1 #-} +{- |++@since 0.3.0+-} instance Foldable1 ((,) c) where     foldMap1 :: Semigroup m => (a -> m) -> (c, a) -> m     foldMap1 f = f . snd@@ -174,6 +201,10 @@     {-# INLINE maximum1 #-}     {-# INLINE minimum1 #-} +{- |++@since 0.3.0+-} instance (Foldable1 f, Foldable1 g) => Foldable1 (Compose f g) where     foldMap1 :: Semigroup m => (a -> m) -> Compose f g a -> m     foldMap1 f = foldMap1 (foldMap1 f) . getCompose@@ -187,11 +218,19 @@     last1 = last1 . last1 . getCompose     {-# INLINE last1 #-} +{- |++@since 0.3.0+-} instance (Foldable1 f, Foldable1 g) => Foldable1 (Product f g) where     foldMap1 :: Semigroup m => (a -> m) -> Product f g a -> m     foldMap1 f (Pair a b) = foldMap1 f a <> foldMap1 f b     {-# INLINE foldMap1 #-} +{- |++@since 0.3.0+-} instance (Foldable1 f, Foldable1 g) => Foldable1 (Sum f g) where     foldMap1 :: Semigroup m => (a -> m) -> Sum f g a -> m     foldMap1 f (InL x) = foldMap1 f x@@ -266,6 +305,8 @@  >>> foldl1' (++) ([1,2] :| [[3,4], [5,6]]) [1,2,3,4,5,6]++@since 0.3.0 -} foldl1' :: (a -> a -> a) -> NonEmpty a -> a foldl1' _ (x :| [])     = x
src/Relude/Extra/Group.hs view
@@ -1,17 +1,22 @@+{-# LANGUAGE Safe         #-} {-# LANGUAGE TypeFamilies #-}  {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable  Polymorphic grouping functions.++@since 0.1.0 -}  module Relude.Extra.Group-       ( groupBy-       , groupOneBy-       ) where+    ( groupBy+    , groupOneBy+    ) where  import Relude import Relude.Extra.Map@@ -23,6 +28,8 @@  >>> groupBy even [1..6] :: HashMap Bool (NonEmpty Int) fromList [(False,5 :| [3,1]),(True,6 :| [4,2])]++@since 0.1.0 -} groupBy :: forall f t a . (Foldable f, DynamicMap t, Val t ~ NonEmpty a, Monoid t)         => (a -> Key t) -> f a -> t@@ -39,6 +46,8 @@  >>> groupOneBy even [1 .. 6] :: HashMap Bool Int fromList [(False,1),(True,2)]++@since 0.1.0 -} groupOneBy :: forall f t a . (Foldable f, DynamicMap t, Val t ~ a, Monoid t)            => (a -> Key t) -> f a -> t
src/Relude/Extra/Lens.hs view
@@ -1,11 +1,16 @@ {-# LANGUAGE Rank2Types #-}+{-# LANGUAGE Safe       #-}  {- | Copyright:  (c) 2013-2016 Edward Kmett-            (c) 2019 Kowainik+            (c) 2019-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable +@since 0.5.0+ This module aims to provide a minimal implementation of @lens@ package required for basic usage. All functions are compatible with the real @lens@ package therefore if you need to expand to the full version the process should be@@ -70,13 +75,13 @@ /Note:/ here we are using composition of the lenses for @userAddress@ field. If we have  @-adressCityL :: 'Lens'' Address 'Text'+addressCityL :: 'Lens'' Address 'Text' @  then  @-cityL = addressL . adressCityL+cityL = addressL . addressCityL @  Let's say we have some sample user@@ -157,15 +162,15 @@ -}  module Relude.Extra.Lens-       ( Lens'-       , lens-       , view-       , set-       , over-       , (^.)-       , (.~)-       , (%~)-       ) where+    ( Lens'+    , lens+    , view+    , set+    , over+    , (^.)+    , (.~)+    , (%~)+    ) where  import Relude @@ -176,42 +181,65 @@    * @a@ is the type of the value inside of structure   * @s@ is the type of the whole structure++@since 0.5.0 -} type Lens' s a = forall f. Functor f => (a -> f a) -> s -> f s --- | Creates 'Lens'' from the getter and setter.+{- | Creates 'Lens'' from the getter and setter.++@since 0.5.0+-} lens :: (s -> a) -> (s -> a -> s) -> Lens' s a lens getter setter = \f s -> setter s <$> f (getter s) {-# INLINE lens #-} --- | Gets a value out of a structure using a getter.+{- | Gets a value out of a structure using a getter.++@since 0.5.0+-} view :: Lens' s a -> s -> a view l = getConst . l Const {-# INLINE view #-} --- | Sets the given value to the structure using a setter.+{- | Sets the given value to the structure using a setter.++@since 0.5.0+-} set :: Lens' s a -> a -> s -> s set l a = runIdentity . l (const (Identity a)) {-# INLINE set #-} --- | Applies the given function to the target.+{- | Applies the given function to the target.++@since 0.5.0+-} over :: Lens' s a -> (a -> a) -> s -> s over l fa = runIdentity . l (Identity . fa) {-# INLINE over #-} --- | The operator form of 'view' with the arguments flipped.-infixr 4 ^.+{- | The operator form of 'view' with the arguments flipped.++@since 0.5.0+-}+infixl 8 ^. (^.) :: s -> Lens' s a -> a s ^. l = view l s {-# INLINE (^.) #-} --- | The operator form of 'set'.+{- | The operator form of 'set'.++@since 0.5.0+-} infixr 4 .~ (.~) :: Lens' s a -> a -> s -> s (.~) = set {-# INLINE (.~) #-} --- | The operator form of 'over'.+{- | The operator form of 'over'.++@since 0.5.0+-} infixr 4 %~ (%~) :: Lens' s a -> (a -> a) -> s -> s (%~) = over
src/Relude/Extra/Map.hs view
@@ -1,26 +1,29 @@+{-# LANGUAGE Trustworthy  #-} {-# LANGUAGE TypeFamilies #-}  {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable -Contains implementation of polymorhic type classes for data types 'Set' and+Contains implementation of polymorphic type classes for data types 'Set' and 'Map'. -}  module Relude.Extra.Map-       ( StaticMap (..)-       , DynamicMap (..)-       , (!?)-       , notMember-       , lookupDefault+    ( StaticMap (..)+    , DynamicMap (..)+    , (!?)+    , notMember+    , lookupDefault -         -- * To pairs-       , toPairs-       , keys-       , elems-       ) where+      -- * To pairs+    , toPairs+    , keys+    , elems+    ) where  import GHC.Exts (IsList (Item, toList)) @@ -46,6 +49,8 @@  {- | Read-only map or set. Contains polymorphic functions which work for both sets and maps.++@since 0.1.0 -} class StaticMap t where     type Key t :: Type@@ -55,6 +60,10 @@     lookup :: Key t -> t -> Maybe (Val t)     member :: Key t -> t -> Bool +{- |++@since 0.1.0+-} instance Ord k => StaticMap (Map k v) where     type Key (Map k v) = k     type Val (Map k v) = v@@ -66,6 +75,10 @@     member = M.member     {-# INLINE member #-} +{- |++@since 0.1.0+-} instance (Eq k, Hashable k) => StaticMap (HashMap k v) where     type Key (HashMap k v) = k     type Val (HashMap k v) = v@@ -77,6 +90,10 @@     member = HM.member     {-# INLINE member #-} +{- |++@since 0.1.0+-} instance StaticMap (IntMap v) where     type Key (IntMap v) = Int     type Val (IntMap v) = v@@ -88,6 +105,10 @@     member = IM.member     {-# INLINE member #-} +{- |++@since 0.1.0+-} instance Ord a => StaticMap (Set a) where     type Key (Set a) = a     type Val (Set a) = a@@ -99,6 +120,10 @@     lookup k m = guard (member k m) $> k     {-# INLINE lookup #-} +{- |++@since 0.1.0+-} instance (Eq a, Hashable a) => StaticMap (HashSet a) where     type Key (HashSet a) = a     type Val (HashSet a) = a@@ -110,6 +135,10 @@     lookup k m = guard (member k m) $> k     {-# INLINE lookup #-} +{- |++@since 0.1.0+-} instance StaticMap IntSet where     type Key IntSet = Int     type Val IntSet = Int@@ -130,6 +159,7 @@ >>> myHashMap !? 'd' Nothing +@since 0.1.0 -} infixl 9 !? (!?) :: StaticMap t => t -> Key t -> Maybe (Val t)@@ -145,6 +175,7 @@ >>> notMember 'c' myHashMap True +@since 0.1.0 -} notMember :: StaticMap t => Key t -> t -> Bool notMember k = not . member k@@ -160,6 +191,7 @@ >>> lookupDefault "zzz" 'c' myHashMap "zzz" +@since 0.1.0 -} lookupDefault :: StaticMap t               => Val t -- ^ Default value to return.@@ -174,6 +206,8 @@ ----------------------------------------------------------------------------  {- | Modifiable Map.++@since 0.1.0 -} class StaticMap t => DynamicMap t where     -- insertions@@ -184,37 +218,46 @@     delete :: Key t -> t -> t     alter :: (Maybe (Val t) -> Maybe (Val t)) -> Key t -> t -> t +{- |++@since 0.1.0+-} instance Ord k => DynamicMap (Map k v) where     insert     = M.insert-    insertWith = M.insertWith-    delete     = M.delete-    alter      = M.alter-     {-# INLINE insert #-}+    insertWith = M.insertWith     {-# INLINE insertWith #-}+    delete     = M.delete     {-# INLINE delete #-}+    alter      = M.alter     {-# INLINE alter #-} +{- |++@since 0.1.0+-} instance (Eq k, Hashable k) => DynamicMap (HashMap k v) where     insert     = HM.insert-    insertWith = HM.insertWith-    delete     = HM.delete-    alter      = HM.alter-     {-# INLINE insert #-}+    insertWith = HM.insertWith     {-# INLINE insertWith #-}+    delete     = HM.delete     {-# INLINE delete #-}+    alter      = HM.alter     {-# INLINE alter #-} +{- |++@since 0.1.0+-} instance DynamicMap (IntMap v) where     insert     = IM.insert-    insertWith = IM.insertWith-    delete     = IM.delete-    alter      = IM.alter-     {-# INLINE insert #-}+    insertWith = IM.insertWith     {-# INLINE insertWith #-}+    delete     = IM.delete     {-# INLINE delete #-}+    alter      = IM.alter     {-# INLINE alter #-}  ----------------------------------------------------------------------------@@ -228,6 +271,8 @@  >>> toPairs (HashMap.fromList [('a', "xxx"), ('b', "yyy")]) [('a',"xxx"),('b',"yyy")]++@since 0.1.0 -} toPairs :: (IsList t, Item t ~ (a, b)) => t -> [(a, b)] toPairs = toList@@ -236,6 +281,8 @@  >>> keys (HashMap.fromList [('a', "xxx"), ('b', "yyy")]) "ab"++@since 0.1.0 -} keys :: (IsList t, Item t ~ (a, b)) => t -> [a] keys = map fst . toList@@ -244,6 +291,8 @@  >>> elems (HashMap.fromList [('a', "xxx"), ('b', "yyy")]) ["xxx","yyy"]++@since 0.1.0 -} elems :: (IsList t, Item t ~ (a, b)) => t -> [b] elems = map snd . toList
src/Relude/Extra/Newtype.hs view
@@ -1,23 +1,28 @@-{-# LANGUAGE CPP #-}+{-# LANGUAGE CPP  #-}+{-# LANGUAGE Safe #-}  {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable -Functions to ease work with newtypes.+Functions to ease work with @newtypes@.++@since 0.2.0 -}  module Relude.Extra.Newtype-       ( un-       , wrap-       , under-       , under2+    ( un+    , wrap+    , under+    , under2 #if ( __GLASGOW_HASKELL__ != 802 )-       , underF2+    , underF2 #endif-       , (#.)-       ) where+    , (#.)+    ) where  import Relude @@ -33,17 +38,21 @@ 5 >>> un (Size 5) == length ['a', 'x', 'b'] False++@since 0.2.0 -} un :: forall a n . Coercible a n => n -> a un = coerce {-# INLINE un #-} -{- | Wraps value to @newtype@. Behaves exactly as 'un' but has more meaningnful+{- | Wraps value to @newtype@. Behaves exactly as 'un' but has more meaningful name in case you need to convert some value to @newtype@.  >>> newtype Flag = Flag Bool deriving (Show, Eq) >>> wrap False == Flag True False++@since 0.2.0 -} wrap :: forall n a . Coercible a n => a -> n wrap = coerce@@ -58,6 +67,8 @@ >>> newtype Bar = Bar String deriving Show >>> under (filter (== 'a')) (Bar "abacaba") Bar "aaaa"++@since 0.2.0 -} under :: forall n a . Coercible a n => (n -> n) -> (a -> a) under = coerce@@ -70,6 +81,8 @@ 7 >>> under2 @All (<>) True False False++@since 0.3.0 -} under2 :: forall n a . Coercible a n => (n -> n -> n) -> (a -> a -> a) under2 = coerce@@ -83,6 +96,8 @@ 7 >>> underF2 @Max (<>) 'p' 't' 't'++@since 0.3.0 -} underF2 :: forall n a . Coercible a (n a) => (n a -> n a -> n a) -> (a -> a -> a) underF2 = coerce@@ -90,7 +105,9 @@ #endif  {- | Coercible composition. This function allows to write more efficient-implementations of functions compoitions over @newtypes@.+implementations of function compositions over @newtypes@.++@since 0.3.0 -} (#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c) (#.) _f = coerce
src/Relude/Extra/Tuple.hs view
@@ -1,23 +1,30 @@+{-# LANGUAGE Safe          #-} {-# LANGUAGE TupleSections #-}  {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable  Contains utility functions for working with tuples.++@since 0.4.0 -}  module Relude.Extra.Tuple-       ( dup-       , dupe-       , mapToFst-       , mapToSnd-       , mapBoth-       , traverseToFst-       , traverseToSnd-       , traverseBoth-       ) where+    ( dup+    , toFst+    , toSnd+    , fmapToFst+    , fmapToSnd+    , mapToFst+    , mapToSnd+    , traverseToFst+    , traverseToSnd+    , traverseBoth+    ) where  import Relude @@ -35,11 +42,64 @@ dup a = (a, a) {-# INLINE dup #-} --- | See 'dup'.-dupe :: a -> (a, a)-dupe = dup-{-# DEPRECATED dupe "Use 'dup' instead, it has more idiomatic and common name" #-}+{- | Apply a function, with the result in the fst slot,+and the value in the other. +A dual to 'toSnd'.++>>> toFst length [3, 1, 0, 2]+(4,[3,1,0,2])+>>> toFst (+5) 10+(15,10)++@since 0.7.0.0+-}+toFst :: (a -> b) -> a -> (b, a)+toFst f a = (f a, a)+{-# INLINE toFst #-}++{- | Apply a function, with the result in the snd slot,+and the value in the other.++A dual to 'toFst'.++>>> toSnd length [3, 1, 0, 2]+([3,1,0,2],4)+>>> toSnd (+5) 10+(10,15)++@since 0.7.0.0+-}+toSnd :: (a -> b) -> a -> (a, b)+toSnd f a = (a, f a)+{-# INLINE toSnd #-}++{- | Like 'fmap', but also keep the original value in the snd position.++A dual to 'fmapToSnd'.++>>> fmapToFst show [3, 10, 2]+[("3",3),("10",10),("2",2)]++@since 0.7.0.0+-}+fmapToFst :: Functor f => (a -> b) -> f a -> f (b, a)+fmapToFst = fmap . toFst+{-# INLINE fmapToFst #-}++{- | Like 'fmap', but also keep the original value in the fst position.++A dual to 'fmapToFst'.++>>> fmapToSnd show [3, 10, 2]+[(3,"3"),(10,"10"),(2,"2")]++@since 0.7.0.0+-}+fmapToSnd :: Functor f => (a -> b) -> f a -> f (a, b)+fmapToSnd = fmap . toSnd+{-# INLINE fmapToSnd #-}+ {- | Apply a function, with the result in the fst slot, and the value in the other. @@ -47,10 +107,13 @@  >>> mapToFst (+1) 10 (11,10)++@since 0.4.0 -} mapToFst :: (a -> b) -> a -> (b, a)-mapToFst f a = (f a, a)+mapToFst = toFst {-# INLINE mapToFst #-}+{-# DEPRECATED mapToFst "Use 'toFst' from 'Relude.Extra.Tuple' instead" #-}  {- | Apply a function, with the result in the second slot, and the value in the other.@@ -59,20 +122,13 @@  >>> mapToSnd (+1) 10 (10,11)++@since 0.4.0 -} mapToSnd :: (a -> b) -> a -> (a, b)-mapToSnd f a = (a, f a)+mapToSnd = toSnd {-# INLINE mapToSnd #-}--{- | Maps a function over both elements of a tuple.-->>> mapBoth ("Hello " <>) ("Alice", "Bob")-("Hello Alice","Hello Bob")--}-mapBoth :: (a -> b) -> (a, a) -> (b, b)-mapBoth f (a1, a2) = (f a1, f a2)-{-# DEPRECATED mapBoth "Use 'Relude.Extra.Bifunctor.bimapBoth' from \"Relude.Extra.Bifunctor\" instead" #-}-{-# INLINE mapBoth #-}+{-# DEPRECATED mapToSnd "Use 'toSnd' from 'Relude.Extra.Tuple' instead" #-}  {- | Apply a function that returns a value inside of a functor, with the output in the first slot, the input in the second,@@ -85,6 +141,8 @@ Just (11,10) >>> traverseToFst (const Nothing) 10 Nothing++@since 0.5.0 -} traverseToFst :: Functor t => (a -> t b) -> a -> t (b, a) traverseToFst f a = (,a) <$> f a@@ -100,6 +158,8 @@ Just (10,11) >>> traverseToSnd (const Nothing) 10 Nothing++@since 0.5.0 -} traverseToSnd :: Functor t => (a -> t b) -> a -> t (a, b) traverseToSnd f a = (a,) <$> f a
src/Relude/Extra/Type.hs view
@@ -3,26 +3,31 @@ {-# LANGUAGE DataKinds            #-} {-# LANGUAGE ExplicitNamespaces   #-} {-# LANGUAGE PolyKinds            #-}+{-# LANGUAGE Safe                 #-} {-# LANGUAGE TypeFamilies         #-} {-# LANGUAGE TypeOperators        #-} {-# LANGUAGE UndecidableInstances #-}  {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable  Contains useful utilities to work with Types.++@since 0.4.0 -}  module Relude.Extra.Type-       ( typeName-       , type (++)-       , AllHave-       , Elem-       , Fst-       , Snd-       ) where+    ( typeName+    , type (++)+    , AllHave+    , Elem+    , Fst+    , Snd+    ) where  import Relude @@ -48,6 +53,8 @@ "[Char]" >>> typeName @(Maybe Int) "Maybe Int"++@since 0.4.0 -} typeName :: forall a. Typeable a => Text #if ( __GLASGOW_HASKELL__ >= 802 )@@ -59,6 +66,8 @@  {- | Concatenates type-level lists. +#if ( __GLASGOW_HASKELL__ >= 806 )+ >>> :kind! '[ 'Just 5, 'Nothing] ++ '[ 'Just 3, 'Nothing, 'Just 1] '[ 'Just 5, 'Nothing] ++ '[ 'Just 3, 'Nothing, 'Just 1] :: [Maybe                                                               Nat]@@ -67,6 +76,8 @@ >>> :kind! '[] ++ '[ 'Just 3, 'Nothing, 'Just 1] '[] ++ '[ 'Just 3, 'Nothing, 'Just 1] :: [Maybe Nat] = '[ 'Just 3, 'Nothing, 'Just 1]++#endif  @since 0.6.0.0 -}
src/Relude/Extra/Validation.hs view
@@ -1,20 +1,59 @@+{-# OPTIONS_GHC -Wno-redundant-constraints #-}+ {-# LANGUAGE CPP                  #-} {-# LANGUAGE ConstraintKinds      #-} {-# LANGUAGE DataKinds            #-} {-# LANGUAGE LambdaCase           #-}+{-# LANGUAGE Safe                 #-} {-# LANGUAGE TypeFamilies         #-} {-# LANGUAGE TypeOperators        #-} {-# LANGUAGE UndecidableInstances #-} +#if __GLASGOW_HASKELL__ > 802+{-# LANGUAGE DerivingStrategies   #-}+#endif+ {- | Copyright:  (c) 2014 Chris Allen, Edward Kmett-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Experimental+Portability: Portable +@since 0.4.0++= Attention++__⚠️ Warning ⚠️__++This module is now deprecated @since 0.7.0.0.+The whole module will be removed in the upcoming release.++== Migration rules++The module is deprecated in favour of+[validation-selective](https://hackage.haskell.org/package/validation-selective).+The package has the identical functionality, so can be easily migrated to.++If you use "Relude.Extra.Validation" in you project you need to:++1. Add @validation-selective@ into the @build-depends@ section of your @.cabal@+   file.+2. Change imports of "Relude.Extra.Validation" to "Validation":++    @+    -- Was:+    import Relude.Extra.Validation (Validation (..), ..)+    -- Become:+    import Validation (Validation (..), ..)+    @++= Description+ 'Validation' is a monoidal sibling to 'Either' but 'Validation' doesn't have a 'Monad' instance. 'Validation' allows to accumulate all errors instead of-short-circuting on the first error so you can display all possible errors at+short-circuiting on the first error so you can display all possible errors at once. Common use-cases include:  1. Validating each input of a form with multiple inputs.@@ -32,12 +71,12 @@ -}  module Relude.Extra.Validation-       ( -- * How to use-         -- $use-         Validation(..)-       , validationToEither-       , eitherToValidation-       ) where+    ( -- * How to use+      -- $use+      Validation(..)+    , validationToEither+    , eitherToValidation+    ) where  import GHC.TypeLits (ErrorMessage (..), TypeError) @@ -107,7 +146,12 @@ data Validation e a     = Failure e     | Success a+#if __GLASGOW_HASKELL__ > 802+    deriving stock (Eq, Ord, Show)+#else     deriving (Eq, Ord, Show)+#endif+{-# DEPRECATED Validation "Use 'Validation' from 'validation-selective' instead"#-}  instance Functor (Validation e) where     fmap :: (a -> b) -> Validation e a -> Validation e b@@ -153,12 +197,16 @@  @since 0.6.0.0 -}-instance (Semigroup e, Monoid a) => Monoid (Validation e a) where+instance (Semigroup e, Semigroup a, Monoid a) => Monoid (Validation e a) where     mempty :: Validation e a     mempty = Success mempty     {-# INLINE mempty #-} -{- | This instance if the most important instance for the 'Validation' data+    mappend :: Validation e a -> Validation e a -> Validation e a+    mappend = (<>)+    {-# INLINE mappend #-}++{- | This instance is the most important instance for the 'Validation' data type. It's responsible for the many implementations. And it allows to accumulate errors while performing validation or combining the results in the applicative style.@@ -337,6 +385,7 @@     Failure e -> Left e     Success a -> Right a {-# INLINE validationToEither #-}+{-# DEPRECATED validationToEither "Use 'validationToEither' from 'validation-selective' instead"#-}  {- | Transform an 'Either' into a 'Validation'. @@ -351,6 +400,7 @@     Left e  -> Failure e     Right a -> Success a {-# INLINE eitherToValidation #-}+{-# DEPRECATED eitherToValidation "Use 'eitherToValidation' from 'validation-selective' instead"#-}  ---------------------------------------------------------------------------- -- Custom errors
src/Relude/File.hs view
@@ -1,9 +1,13 @@+{-# LANGUAGE Safe #-}+ {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Lifted to 'MonadIO' families of file processing functions for 'Text', 'LText',+Lifted to 'MonadIO' families of file processing functions for the 'Text', 'LText', 'ByteString' and 'LByteString' types.  These functions are lifted which means that you can also use them inside@@ -13,31 +17,33 @@ with 'Text' or 'LText' types are system and locale-sensitive (encoding, line-endings). If you want binary data, use 'ByteString' functions (they are also faster since they don't check encoding). However, you can then decode that-data with the help of functions from the @"Relude.String.Conversion"@ module, e. g.+data with the help of functions from the "Relude.String.Conversion" module, e. g. 'Relude.String.Conversion.decodeUtf8'.++@since 0.3.0 -}  module Relude.File-       ( -- * Text-         readFileText-       , writeFileText-       , appendFileText+    ( -- * Text+      readFileText+    , writeFileText+    , appendFileText -         -- * Lazy Text-       , readFileLText-       , writeFileLText-       , appendFileLText+      -- * Lazy Text+    , readFileLText+    , writeFileLText+    , appendFileLText -         -- * ByteString-       , readFileBS-       , writeFileBS-       , appendFileBS+      -- * ByteString+    , readFileBS+    , writeFileBS+    , appendFileBS -         -- * Lazy ByteString-       , readFileLBS-       , writeFileLBS-       , appendFileLBS-       ) where+      -- * Lazy ByteString+    , readFileLBS+    , writeFileLBS+    , appendFileLBS+    ) where  import Relude.Base (FilePath, IO) import Relude.Function ((.))@@ -49,23 +55,33 @@ import qualified Data.Text.IO as T import qualified Data.Text.Lazy.IO as LT + ---------------------------------------------------------------------------- -- Text ---------------------------------------------------------------------------- --- | Lifted version of 'T.readFile'.+{- | Lifted version of 'T.readFile'.++@since 0.3.0+-} readFileText :: MonadIO m => FilePath -> m Text readFileText = liftIO . T.readFile {-# SPECIALIZE readFileText :: FilePath -> IO Text #-} {-# INLINE     readFileText #-} --- | Lifted version of 'T.writeFile'.+{- | Lifted version of 'T.writeFile'.++@since 0.3.0+-} writeFileText :: MonadIO m => FilePath -> Text -> m () writeFileText p = liftIO . T.writeFile p {-# SPECIALIZE writeFileText :: FilePath -> Text -> IO () #-} {-# INLINE     writeFileText #-} --- | Lifted version of 'T.appendFile'.+{- | Lifted version of 'T.appendFile'.++@since 0.3.0+-} appendFileText :: MonadIO m => FilePath -> Text -> m () appendFileText p = liftIO . T.appendFile p {-# SPECIALIZE appendFileText :: FilePath -> Text -> IO () #-}@@ -75,19 +91,28 @@ -- Lazy Text ---------------------------------------------------------------------------- --- | Lifted version of 'LT.readFile'.+{- | Lifted version of 'LT.readFile'.++@since 0.3.0+-} readFileLText :: MonadIO m => FilePath -> m LText readFileLText = liftIO . LT.readFile {-# SPECIALIZE readFileLText :: FilePath -> IO LText #-} {-# INLINE     readFileLText #-} --- | Lifted version of 'LT.writeFile'.+{- | Lifted version of 'LT.writeFile'.++@since 0.3.0+-} writeFileLText :: MonadIO m => FilePath -> LText -> m () writeFileLText p = liftIO . LT.writeFile p {-# SPECIALIZE writeFileLText :: FilePath -> LText -> IO () #-} {-# INLINE     writeFileLText #-} --- | Lifted version of 'LT.appendFile'.+{- | Lifted version of 'LT.appendFile'.++@since 0.3.0+-} appendFileLText :: MonadIO m => FilePath -> LText -> m () appendFileLText p = liftIO . LT.appendFile p {-# SPECIALIZE appendFileLText :: FilePath -> LText -> IO () #-}@@ -97,19 +122,28 @@ -- ByteString ---------------------------------------------------------------------------- --- | Lifted version of 'BS.readFile'.+{- | Lifted version of 'BS.readFile'.++@since 0.3.0+-} readFileBS :: MonadIO m => FilePath -> m ByteString readFileBS = liftIO . BS.readFile {-# SPECIALIZE readFileBS :: FilePath -> IO ByteString #-} {-# INLINE     readFileBS #-} --- | Lifted version of 'BS.writeFile'.+{- | Lifted version of 'BS.writeFile'.++@since 0.3.0+-} writeFileBS :: MonadIO m => FilePath -> ByteString -> m () writeFileBS p = liftIO . BS.writeFile p {-# SPECIALIZE writeFileBS :: FilePath -> ByteString -> IO () #-} {-# INLINE     writeFileBS #-} --- | Lifted version of 'BS.appendFile'.+{- | Lifted version of 'BS.appendFile'.++@since 0.3.0+-} appendFileBS :: MonadIO m => FilePath -> ByteString -> m () appendFileBS p = liftIO . BS.appendFile p {-# SPECIALIZE appendFileBS :: FilePath -> ByteString -> IO () #-}@@ -119,19 +153,28 @@ -- Lazy ByteString ---------------------------------------------------------------------------- --- | Lifted version of 'LBS.readFile'.+{- | Lifted version of 'LBS.readFile'.++@since 0.3.0+-} readFileLBS :: MonadIO m => FilePath -> m LByteString readFileLBS = liftIO . LBS.readFile {-# SPECIALIZE readFileLBS :: FilePath -> IO LByteString #-} {-# INLINE     readFileLBS #-} --- | Lifted version of 'LBS.writeFile'.+{- | Lifted version of 'LBS.writeFile'.++@since 0.3.0+-} writeFileLBS :: MonadIO m => FilePath -> LByteString -> m () writeFileLBS p = liftIO . LBS.writeFile p {-# SPECIALIZE writeFileLBS :: FilePath -> LByteString -> IO () #-} {-# INLINE     writeFileLBS #-} --- | Lifted version of 'LBS.appendFile'.+{- | Lifted version of 'LBS.appendFile'.++@since 0.3.0+-} appendFileLBS :: MonadIO m => FilePath -> LByteString -> m () appendFileLBS p = liftIO . LBS.appendFile p {-# SPECIALIZE appendFileLBS :: FilePath -> LByteString -> IO () #-}
src/Relude/Foldable.hs view
@@ -1,15 +1,29 @@+{-# LANGUAGE Safe #-}+ {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -This module exports all 'Foldable' and 'Traversable' related stuff.+This module provides 'Foldable' and 'Traversable' related types and functions. -}  module Relude.Foldable-       ( module Relude.Foldable.Fold-       , module Relude.Foldable.Reexport-       ) where+    ( module Relude.Foldable.Reexport+      -- $reexport+    , module Relude.Foldable.Fold+      -- $fold+    ) where  import Relude.Foldable.Fold import Relude.Foldable.Reexport++{- $reexport+Reexports types and functions from "Data.Foldable" and "Data.Traversable".+-}++{- $fold+Type safe versions and additional functions to 'Foldable'.+-}
src/Relude/Foldable/Fold.hs view
@@ -1,5 +1,8 @@+{-# OPTIONS_GHC -Wno-redundant-constraints #-}+ {-# LANGUAGE DataKinds            #-} {-# LANGUAGE PolyKinds            #-}+{-# LANGUAGE Safe                 #-} {-# LANGUAGE TypeFamilies         #-} {-# LANGUAGE TypeOperators        #-} {-# LANGUAGE UndecidableInstances #-}@@ -7,30 +10,37 @@ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Fixes and additions to 'Foldable'.+Fixes and additions to 'Foldable'. Specifically:++* Space-leak free 'sum' and 'production'+* 'elem' and 'notElem' are forbidden for 'Set' and 'HashSet'+* Additional combinators for common idioms -}  module Relude.Foldable.Fold-       ( flipfoldl'-       , asumMap-       , foldMapA-       , foldMapM+    ( flipfoldl'+    , asumMap+    , foldMapA+    , foldMapM -       , sum-       , product+    , sum+    , product -       , elem-       , notElem+    , elem+    , notElem -       , allM-       , anyM-       , andM-       , orM-       ) where+      -- * Monadic functions+    , allM+    , anyM+    , andM+    , orM+    ) where  import GHC.TypeLits (ErrorMessage (..), Symbol, TypeError) @@ -66,6 +76,8 @@  >>> asumMap (\x -> if x > 2 then Just x else Nothing) [1..4] Just 3++@since 0.4.0 -} asumMap :: forall b m f a . (Foldable f, Alternative m) => (a -> m b) -> f a -> m b asumMap = coerce (foldMap :: (a -> Alt m b) -> f a -> Alt m b)@@ -75,6 +87,8 @@  >>> foldMapA @[Int] (Just . replicate 3) [1..3] Just [1,1,1,2,2,2,3,3,3]++@since 0.1.0 -} foldMapA :: forall b m f a . (Semigroup b, Monoid b, Applicative m, Foldable f) => (a -> m b) -> f a -> m b foldMapA = coerce (foldMap :: (a -> Ap m b) -> f a -> Ap m b)@@ -84,6 +98,8 @@  >>> foldMapM @[Int] (Just . replicate 3) [1..3] Just [1,1,1,2,2,2,3,3,3]++@since 0.1.0 -} foldMapM :: forall b m f a . (Monoid b, Monad m, Foldable f) => (a -> m b) -> f a -> m b foldMapM f xs = foldr step return xs mempty
src/Relude/Foldable/Reexport.hs view
@@ -1,21 +1,26 @@-{-# LANGUAGE CPP #-}+{-# LANGUAGE CPP  #-}+{-# LANGUAGE Safe #-}  {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Reexports "Data.Foldable" and "Data.Traversable". -}  module Relude.Foldable.Reexport-       ( module Data.Foldable-       , module Data.Traversable+    ( -- * @Foldable@ reexports+      module Data.Foldable+    , module Data.Traversable #if MIN_VERSION_base(4,10,0)-       , module Data.Bifoldable-       , module Data.Bitraversable+      -- * @Bi@ reexports+    , module Data.Bifoldable+    , module Data.Bitraversable #endif-       ) where+    ) where  import Data.Foldable (Foldable (fold, foldMap, foldl', foldr, length, null, toList), all, and, any,                       asum, concat, concatMap, find, foldlM, forM_, for_, mapM_, or, sequenceA_,
src/Relude/Function.hs view
@@ -1,19 +1,38 @@+{-# LANGUAGE Safe #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -This module reexports very basic and primitive functions and function combinators.+This module reexports very basic and primitive functions and function+combinators. -}  module Relude.Function-       ( module Control.Arrow-       , module Control.Category-       , module Data.Function-       , identity-       ) where+    ( -- * Reexports+      -- ** "Data.Function" reexports+      (.)+    , ($)+    , (&)+    , id+    , const+    , flip+    , fix+    , on+      -- ** "Control.Category" reexports+    , (>>>)+    , (<<<)+      -- ** "Control.Arrow" reexports+    , (&&&)++      -- * Combinators+    , identity+    ) where  import Control.Arrow ((&&&)) import Control.Category ((<<<), (>>>))
src/Relude/Functor.hs view
@@ -3,17 +3,30 @@ {- | Copyright: (c) 2016 Stephen Diehl            (c) 2016-2018 Serokell-           (c) 2018 Kowainik+           (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Convenient functions to work with 'Functor'. -}  module Relude.Functor-       ( module Relude.Functor.Fmap-       , module Relude.Functor.Reexport-       ) where+    ( module Relude.Functor.Reexport+      -- $reexport+    , module Relude.Functor.Fmap+      -- $fmap+    ) where  import Relude.Functor.Fmap import Relude.Functor.Reexport++{- $reexport+Reexports functionality for 'Functor' and 'Bifunctor' typeclasses.+-}++{- $fmap+Additional useful combinators to work with 'Functor' type class.+For example, '<<$>>' and '??'.+-}
src/Relude/Functor/Fmap.hs view
@@ -4,19 +4,21 @@ {- | Copyright: (c) 2016 Stephen Diehl            (c) 2016-2018 Serokell-           (c) 2018 Kowainik+           (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  This module contains useful functions to work with 'Functor' type class. -}  module Relude.Functor.Fmap-       ( (<<$>>)-       , (<&>)-       , flap-       , (??)-       ) where+    ( (<<$>>)+    , (<&>)+    , flap+    , (??)+    ) where  import Relude.Function ((.)) import Relude.Functor.Reexport (Functor (..))@@ -53,6 +55,8 @@  >>> flap (++) "relude" "P" "Prelude"++@since 0.3.0 -} flap :: Functor f => f (a -> b) -> a -> f b flap ff x = (\f -> f x) <$> ff@@ -65,6 +69,8 @@  >>> Just (+3) ?? 5 Just 8++@since 0.3.0 -} infixl 4 ?? (??) :: Functor f => f (a -> b) -> a -> f b
src/Relude/Functor/Reexport.hs view
@@ -4,22 +4,24 @@ {- | Copyright: (c) 2016 Stephen Diehl            (c) 2016-2018 Serokell-           (c) 2018 Kowainik+           (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Reexports functionality regarding 'Functor' and 'Bifunctor' typeclasses. -}  module Relude.Functor.Reexport-       ( module Data.Bifunctor-       , module Data.Functor-       , module Data.Functor.Compose-       , module Data.Functor.Identity+    ( module Data.Bifunctor+    , module Data.Functor+    , module Data.Functor.Compose+    , module Data.Functor.Identity #if MIN_VERSION_base(4,12,0)-       , module Data.Functor.Contravariant+    , module Data.Functor.Contravariant #endif-       ) where+    ) where  import Data.Bifunctor (Bifunctor (..)) import Data.Functor (Functor (..), void, ($>), (<$>))
src/Relude/Lifted.hs view
@@ -1,27 +1,97 @@+{-# LANGUAGE Safe #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Lifted versions of base functions.  These functions are lifted in a sense that you can use them inside various monad transformers without adding 'Relude.liftIO' calls explicitly. However, you still can use all these functions inside plain 'Relude.IO' monad as usual.++=== Example++==== @base@++With the @base@ function, you can easily work with these functions in the+'Relude.IO' monad:++@+__main__ :: 'Relude.IO' ()+__main__ = __do__+    x <- 'Data.Text.getLine'+    'Prelude.print' x+@++However, to work in 'Relude.MonadIO' you already need to "lift" them:++@+__main__ :: 'Relude.MonadIO' m => m ()+__main__ = __do__+    x <- 'Relude.liftIO' 'Data.Text.getLine'+    'Relude.liftIO' ('Prelude.print' x)+@++==== @relude@++In the meantime, @relude@ provides these function that can work in 'Relude.IO'+the same way:++@+__main__ :: 'Relude.IO' ()+__main__ = __do__+    x <- 'getLine'+    'print' x+@++But also allows you to work in the 'Relude.MonadIO' monads more easily:++@+__main__ :: 'Relude.MonadIO' m => m ()+__main__ = __do__+    x <- 'getLine'+    'print' x+@+ -}  module Relude.Lifted-       ( module Relude.Lifted.Concurrent-       , module Relude.Lifted.Exit-       , module Relude.Lifted.File-       , module Relude.Lifted.IORef-       , module Relude.Lifted.Terminal-       ) where+    ( module Relude.Lifted.Concurrent+      -- $concurrent+    , module Relude.Lifted.IORef+      -- $ioref+    , module Relude.Lifted.Exit+      -- $exit+    , module Relude.Lifted.File+      -- $file+    , module Relude.Lifted.Terminal+      -- $terminal+    ) where  import Relude.Lifted.Concurrent import Relude.Lifted.Exit import Relude.Lifted.File import Relude.Lifted.IORef import Relude.Lifted.Terminal++{- $concurrent+Lifted 'MVar' and 'STM' functions.+-}+{- $exit+Lifted versions of functions that work with exit processes.+-}+{- $file+Lifted versions of functions working with files and common 'Relude.IO'.+-}+{- $ioref+Lifted reexports from "Data.IORef" module.+-}+{- $terminal+Lifted functions to work with stdin and stdout.+-}
src/Relude/Lifted/Concurrent.hs view
@@ -1,41 +1,64 @@-{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE Safe #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Lifted 'MVar' and 'STM' functions. -}  module Relude.Lifted.Concurrent-       ( -- * MVar-         MVar-       , newEmptyMVar-       , newMVar-       , putMVar-       , readMVar-       , swapMVar-       , takeMVar-       , tryPutMVar-       , tryReadMVar-       , tryTakeMVar+    ( -- * MVar+      MVar+    , newEmptyMVar+    , newMVar+    , putMVar+    , readMVar+    , swapMVar+    , takeMVar+    , tryPutMVar+    , tryReadMVar+    , tryTakeMVar -         -- * STM-       , STM-       , TVar-       , atomically-       , newTVarIO-       , readTVarIO-       , STM.modifyTVar'-       , STM.newTVar-       , STM.readTVar-       , STM.writeTVar-       ) where+      -- * STM+    , STM+    , atomically+    , STM.throwSTM+    , STM.catchSTM +      -- * TVar+    , TVar+    , newTVarIO+    , readTVarIO+    , STM.modifyTVar'+    , STM.newTVar+    , STM.readTVar+    , STM.writeTVar++      -- * TMVar+    , TMVar+    , STM.newTMVar+    , STM.newEmptyTMVar+    , newTMVarIO+    , newEmptyTMVarIO+    , STM.takeTMVar+    , STM.putTMVar+    , STM.readTMVar+    , STM.tryReadTMVar+    , STM.swapTMVar+    , STM.tryTakeTMVar+    , STM.tryPutTMVar+    , STM.isEmptyTMVar+    , STM.mkWeakTMVar+    ) where+ import Control.Concurrent.MVar (MVar)+import Control.Concurrent.STM.TMVar (TMVar) import Control.Concurrent.STM.TVar (TVar) import Control.Monad.STM (STM) @@ -46,10 +69,15 @@  import qualified Control.Concurrent.MVar as CCM (newEmptyMVar, newMVar, putMVar, readMVar, swapMVar,                                                  takeMVar, tryPutMVar, tryReadMVar, tryTakeMVar)+import qualified Control.Concurrent.STM.TMVar as STM (isEmptyTMVar, mkWeakTMVar, newEmptyTMVar,+                                                      newEmptyTMVarIO, newTMVar, newTMVarIO,+                                                      putTMVar, readTMVar, swapTMVar, takeTMVar,+                                                      tryPutTMVar, tryReadTMVar, tryTakeTMVar) import qualified Control.Concurrent.STM.TVar as STM (modifyTVar', newTVar, newTVarIO, readTVar,                                                      readTVarIO, writeTVar)-import qualified Control.Monad.STM as STM (atomically)+import qualified Control.Monad.STM as STM (atomically, catchSTM, throwSTM) + ---------------------------------------------------------------------------- -- Lifted Control.Concurrent.MVar ----------------------------------------------------------------------------@@ -129,3 +157,15 @@ readTVarIO = liftIO . STM.readTVarIO {-# INLINE readTVarIO #-} {-# SPECIALIZE readTVarIO :: TVar a -> IO a #-}++-- | Lifted to 'MonadIO' version of 'STM.newTMVarIO'.+newTMVarIO :: MonadIO m => a -> m (TMVar a)+newTMVarIO = liftIO . STM.newTMVarIO+{-# INLINE newTMVarIO #-}+{-# SPECIALIZE newTMVarIO :: a -> IO (TMVar a) #-}++-- | Lifted to 'MonadIO' version of 'STM.newEmptyTMVarIO'.+newEmptyTMVarIO :: MonadIO m => m (TMVar a)+newEmptyTMVarIO = liftIO STM.newEmptyTMVarIO+{-# INLINE newEmptyTMVarIO #-}+{-# SPECIALIZE newEmptyTMVarIO :: IO (TMVar a) #-}
src/Relude/Lifted/Exit.hs view
@@ -3,25 +3,28 @@ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Lifted versions of functions that work with exit processes. -}  module Relude.Lifted.Exit-       ( exitWith-       , exitFailure-       , exitSuccess-       , die-       ) where+    ( exitWith+    , exitFailure+    , exitSuccess+    , die+    ) where  import Control.Monad.Trans (MonadIO, liftIO) import Data.String (String) import System.Exit (ExitCode)  import qualified System.Exit as XIO+  -- $setup -- >>> import Relude
src/Relude/Lifted/File.hs view
@@ -1,18 +1,22 @@+{-# LANGUAGE Safe #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Lifted versions of functions working with files and common IO. -}  module Relude.Lifted.File-       ( readFile-       , writeFile-       , appendFile-       ) where+    ( readFile+    , writeFile+    , appendFile+    ) where  import Relude.Base (FilePath, IO) import Relude.Function ((.))
src/Relude/Lifted/IORef.hs view
@@ -1,26 +1,30 @@-{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE Safe #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Lifted reexports from 'Data.IORef' module.+Lifted reexports from "Data.IORef" module. -}  module Relude.Lifted.IORef-       ( IORef-       , atomicModifyIORef-       , atomicModifyIORef'-       , atomicWriteIORef-       , modifyIORef-       , modifyIORef'-       , newIORef-       , readIORef-       , writeIORef-       ) where+    ( IORef+    , atomicModifyIORef+    , atomicModifyIORef'+    , atomicModifyIORef_+    , atomicModifyIORef'_+    , atomicWriteIORef+    , modifyIORef+    , modifyIORef'+    , newIORef+    , readIORef+    , writeIORef+    ) where  import Control.Monad.Trans (MonadIO, liftIO) import Data.Function (($), (.))@@ -79,6 +83,8 @@ >>> readIORef ref 48 +* To avoid space-leaks, see 'modifyIORef'' for stricter updates+* For atomic updates, see 'atomicModifyIORef' -} modifyIORef :: MonadIO m => IORef a -> (a -> a) -> m () modifyIORef ref how = liftIO $ Ref.modifyIORef ref how@@ -92,6 +98,8 @@ >>> readIORef ref 45 +* For lazier updates, see 'modifyIORef'+* For atomic updates, see 'atomicModifyIORef'' -} modifyIORef' :: MonadIO m => IORef a -> (a -> a) -> m () modifyIORef' ref how = liftIO $ Ref.modifyIORef' ref how@@ -106,6 +114,8 @@ >>> readIORef ref 42 +* To avoid space-leaks, see 'atomicModifyIORef'' for stricter updates+* If you are not interested in the return value, see 'atomicModifyIORef_' -} atomicModifyIORef :: MonadIO m => IORef a -> (a -> (a, b)) -> m b atomicModifyIORef ref how = liftIO $ Ref.atomicModifyIORef ref how@@ -120,11 +130,45 @@ >>> readIORef ref 42 +* For lazier updates, see 'atomicModifyIORef'+* If you are not interested in the return value, see 'atomicModifyIORef'_' -} atomicModifyIORef' :: MonadIO m => IORef a -> (a -> (a, b)) -> m b atomicModifyIORef' ref how = liftIO $ Ref.atomicModifyIORef' ref how {-# INLINE atomicModifyIORef' #-} {-# SPECIALIZE atomicModifyIORef' :: IORef a -> (a -> (a, b)) -> IO b #-}++{- | Version of 'atomicModifyIORef' that discards return value. Useful+when you want to update 'IORef' but not interested in the returning+result.++>>> ref <- newIORef 42+>>> atomicModifyIORef_ ref (`div` 2)+>>> readIORef ref+21++@since 0.7.0.0+-}+atomicModifyIORef_ :: MonadIO m => IORef a -> (a -> a) -> m ()+atomicModifyIORef_ ref f = atomicModifyIORef ref $ \a -> (f a, ())+{-# INLINE atomicModifyIORef_ #-}+{-# SPECIALIZE atomicModifyIORef_ :: IORef a -> (a -> a) -> IO () #-}++{- | Version of 'atomicModifyIORef'' that discards return value. Useful+when you want to update 'IORef' but not interested in the returning+result.++>>> ref <- newIORef 42+>>> atomicModifyIORef'_ ref (`div` 2)+>>> readIORef ref+21++@since 0.7.0.0+-}+atomicModifyIORef'_ :: MonadIO m => IORef a -> (a -> a) -> m ()+atomicModifyIORef'_ ref f = atomicModifyIORef' ref $ \a -> (f a, ())+{-# INLINE atomicModifyIORef'_ #-}+{-# SPECIALIZE atomicModifyIORef'_ :: IORef a -> (a -> a) -> IO () #-}  {- | Lifted version of 'Ref.atomicWriteIORef'. 
src/Relude/Lifted/Terminal.hs view
@@ -1,19 +1,23 @@-{-# LANGUAGE ExplicitForAll #-}+{-# LANGUAGE Safe #-}  {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Lifted functions to work with stdin and stdout.++@since 0.3.0 -}  module Relude.Lifted.Terminal-       ( getLine-       , print-       , putStr-       , putStrLn-       ) where+    ( getLine+    , print+    , putStr+    , putStrLn+    ) where  import Relude.Base (IO, Show) import Relude.Function ((.))
src/Relude/List.hs view
@@ -1,20 +1,24 @@-{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE Safe #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Utility functions to work with lists.+Utility functions to work with lists and 'NonEmpty' lists. -}  module Relude.List-       ( module Relude.List.NonEmpty-       , module Relude.List.Reexport-       , (!!?)-       ) where+    ( module Relude.List.Reexport+      -- $reexport+    , module Relude.List.NonEmpty+      -- $nonempty+    , (!!?)+    ) where   import Relude.Base ((<))@@ -56,3 +60,18 @@     go j (_:ys) = go (j - 1) ys     go _ []     = Nothing {-# INLINE (!!?) #-}++{- $reexport+Most of the "Data.List" types and function.++Note, that list partial functions (e.g. 'Data.List.head') are not exported from+"Data.List".+Instead @relude@ provides safe functions that work with+'Data.List.NonEmpty.NonEmpty'. You can find them in the+"Relude.List.NonEmpty" module instead.+-}++{- $nonempty+Reexports from "Data.List.NonEmpty" and additional safe functions to work with+list type in terms of 'NonEmpty'.+-}
src/Relude/List/NonEmpty.hs view
@@ -1,37 +1,114 @@-{-# LANGUAGE Safe #-}+{-# LANGUAGE ConstraintKinds      #-}+{-# LANGUAGE DataKinds            #-}+{-# LANGUAGE Safe                 #-}+{-# LANGUAGE TypeFamilies         #-}+{-# LANGUAGE TypeOperators        #-}+{-# LANGUAGE UndecidableInstances #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -This module contains safe functions to work with list type in terms of 'NonEmpty'.+This module contains reexports from "Data.List.NonEmpty" and safe functions to+work with list type in terms of 'NonEmpty'.++Note, that "Relude" reexports 'head', 'tail', 'init', 'last' from+"Data.List.NonEmpty" instead of the "Data.List", so these functions are safe to+use.+++------------+--------------+-----------------------++|            |    @base@    |       @relude@        |++============+==============+=======================++| __'head'__ | @[a] -> a@   | @'NonEmpty' a -> a@   |++------------+--------------+-----------------------++| __'tail'__ | @[a] -> [a]@ | @'NonEmpty' a -> [a]@ |++------------+--------------+-----------------------++| __'last'__ | @[a] -> a@   | @'NonEmpty' a -> a@   |++------------+--------------+-----------------------++| __'init'__ | @[a] -> [a]@ | @'NonEmpty' a -> [a]@ |++------------+--------------+-----------------------+++@relude@ also provides custom type error for better experience with transition+from lists to 'NonEmpty' with those functions.+++Let's examine the behaviour of the @relude@ list functions comparing to the+corresponding @base@ one on the example of the 'head' function:+++-----------------+-----------------------------------------++|                 |         'head'                          |++=================+=========================================++| __@base@__      | @[a] -> a@                              |++-----------------+-----------------------------------------++| __@relude@__    | @'NonEmpty' a -> a@                     |++-----------------+-----------------------------------------++| Example         | @> 'Data.List.head' [1..5]@             |+| with list       +-----------------------------------------++| __@base@__      | @1@                                     |++-----------------+-----------------------------------------++| Example         | @> 'Data.List.head' []@                 |+| with empty list +-----------------------------------------++| __@base@__      |@*** Exception: Prelude.head: empty list@|++-----------------+-----------------------------------------++| Example         |@> 'head' $ 1 :| [2..5]@                 |+| with 'NonEmpty' +-----------------------------------------++| __@relude@__    | @1@                                     |++-----------------+-----------------------------------------++| Example         | @> 'viaNonEmpty' 'head' [1..5]@         |+| with list       +-----------------------------------------++| __@relude@__    | @'Just' 1@                              |++-----------------+-----------------------------------------++| Example         |@> 'viaNonEmpty' 'head' []@              |+| with empty list +-----------------------------------------++| __@relude@__    | @'Nothing'@                             |++-----------------+-----------------------------------------+++@since 0.2.0 -}  module Relude.List.NonEmpty-       ( viaNonEmpty-       , whenNotNull-       , whenNotNullM-       ) where+    ( -- * Reexports from "DataList.NonEmpty"+      NonEmpty (..)+    , nonEmpty+    , head+    , tail+    , last+    , init +      -- * Combinators+    , viaNonEmpty+    , whenNotNull+    , whenNotNullM+    ) where++import Data.List.NonEmpty (NonEmpty (..), nonEmpty)+import GHC.TypeLits (ErrorMessage (..), Symbol, TypeError)+ import Relude.Applicative (Applicative, pass)+import Relude.Base (Constraint, Type) import Relude.Function ((.)) import Relude.Functor (fmap)-import Relude.List.Reexport (NonEmpty (..), nonEmpty) import Relude.Monad (Maybe (..), Monad (..)) +import qualified Data.List.NonEmpty as NE (head, init, last, tail) + -- $setup -- >>> import Relude -{- | For safe work with lists using functinons for 'NonEmpty'.+{- | For safe work with lists using functions for 'NonEmpty'.  >>> viaNonEmpty head [1] Just 1 >>> viaNonEmpty head [] Nothing++@since 0.1.0 -} viaNonEmpty :: (NonEmpty a -> b) -> [a] -> Maybe b viaNonEmpty f = fmap f . nonEmpty@@ -52,3 +129,187 @@ whenNotNullM :: Monad m => m [a] -> (NonEmpty a -> m ()) -> m () whenNotNullM ml f = ml >>= \l -> whenNotNull l f {-# INLINE whenNotNullM #-}+++-- | For tracking usage of ordinary list with @head@-like functions.+type IsNonEmpty+    (f :: Type -> Type)  -- Container, e.g. NonEmpty or []+    (a :: Type)          -- Type of the element+    (res :: Type)        -- Type of the result of the work of the function+    (fun :: Symbol)      -- Function name+    = (f ~ NonEmpty, CheckNonEmpty f a res fun)++type family CheckNonEmpty+    (f :: Type -> Type)+    (a :: Type)+    (res :: Type)+    (fun :: Symbol)+    :: Constraint+  where+    CheckNonEmpty NonEmpty _ _ _ = ()+    CheckNonEmpty [] a res fun = TypeError+        ( 'Text "'" ':<>: 'Text fun ':<>: 'Text "' works with 'NonEmpty', not ordinary lists."+        ':$$: 'Text "Possible fix:"+        ':$$: 'Text "    Replace: [" ':<>: 'ShowType a ':<>: 'Text "]"+        ':$$: 'Text "    With:    NonEmpty " ':<>: 'ShowType a+        ':$$: 'Text ""+        ':$$: 'Text "However, you can use '" ':<>: 'Text fun ':<>: 'Text "' with the ordinary lists."+        ':$$: 'Text "Apply 'viaNonEmpty' function from relude:"+        ':$$: 'Text "    viaNonEmpty " ':<>: 'Text fun ':<>: 'Text " (yourList)"+        ':$$: 'Text "Note, that this will return 'Maybe " ':<>: 'ShowType res ':<>: 'Text "'"+        ':$$: 'Text "therefore it is a safe function unlike '" ':<>: 'Text fun ':<>: 'Text "' from the standard Prelude"+        )+    CheckNonEmpty t a _ fun = TypeError+        ( 'Text "'"+        ':<>: 'Text fun+        ':<>: 'Text "' works with 'NonEmpty "+        ':<>: 'ShowType a+        ':<>: 'Text "' lists"+        ':$$: 'Text "But given: "+        ':<>: 'ShowType t+        ':<>: 'Text " "+        ':<>: 'ShowType a+        )+++{- | @O(1)@. Extracts the first element of a 'NonEmpty' list.++Actual type of this function is the following:++@+head :: 'NonEmpty' a -> a+@++but it was given a more complex type to provide friendlier compile time errors.++>>> head ('a' :| "bcde")+'a'+>>> head [0..5 :: Int]+...+... 'head' works with 'NonEmpty', not ordinary lists.+      Possible fix:+          Replace: [Int]+          With:    NonEmpty Int+...+      However, you can use 'head' with the ordinary lists.+      Apply 'viaNonEmpty' function from relude:+          viaNonEmpty head (yourList)+      Note, that this will return 'Maybe Int'+      therefore it is a safe function unlike 'head' from the standard Prelude+...+>>> head (Just 'a')+...+... 'head' works with 'NonEmpty Char' lists+      But given: Maybe Char+...+-}+head :: IsNonEmpty f a a "head" => f a -> a+head = NE.head+{-# INLINE head #-}++{- | @O(n)@. Return all the elements of a 'NonEmpty' list except the last one+element.++Actual type of this function is the following:++@+init :: 'NonEmpty' a -> [a]+@++but it was given a more complex type to provide friendlier compile time errors.++>>> init ('a' :| "bcde")+"abcd"+>>> init [0..5 :: Int]+...+... 'init' works with 'NonEmpty', not ordinary lists.+      Possible fix:+          Replace: [Int]+          With:    NonEmpty Int+...+      However, you can use 'init' with the ordinary lists.+      Apply 'viaNonEmpty' function from relude:+          viaNonEmpty init (yourList)+      Note, that this will return 'Maybe [Int]'+      therefore it is a safe function unlike 'init' from the standard Prelude+...+>>> init (Just 'a')+...+... 'init' works with 'NonEmpty Char' lists+      But given: Maybe Char+...+-}+init :: IsNonEmpty f a [a] "init" => f a -> [a]+init = NE.init+{-# INLINE init #-}++{- | @O(n)@. Extracts the last element of a 'NonEmpty' list.++Actual type of this function is the following:++@+last :: 'NonEmpty' a -> a+@++but it was given a more complex type to provide friendlier compile time errors.++>>> last ('a' :| "bcde")+'e'+>>> last [0..5 :: Int]+...+... 'last' works with 'NonEmpty', not ordinary lists.+      Possible fix:+          Replace: [Int]+          With:    NonEmpty Int+...+      However, you can use 'last' with the ordinary lists.+      Apply 'viaNonEmpty' function from relude:+          viaNonEmpty last (yourList)+      Note, that this will return 'Maybe Int'+      therefore it is a safe function unlike 'last' from the standard Prelude+...+>>> last (Just 'a')+...+... 'last' works with 'NonEmpty Char' lists+      But given: Maybe Char+...+-}+last :: IsNonEmpty f a a "last" => f a -> a+last = NE.last+{-# INLINE last #-}++{- | @O(1)@. Return all the elements of a 'NonEmpty' list after the head+element.++Actual type of this function is the following:++@+tail :: 'NonEmpty' a -> [a]+@++but it was given a more complex type to provide friendlier compile time errors.++>>> tail ('a' :| "bcde")+"bcde"+>>> tail [0..5 :: Int]+...+... 'tail' works with 'NonEmpty', not ordinary lists.+      Possible fix:+          Replace: [Int]+          With:    NonEmpty Int+...+      However, you can use 'tail' with the ordinary lists.+      Apply 'viaNonEmpty' function from relude:+          viaNonEmpty tail (yourList)+      Note, that this will return 'Maybe [Int]'+      therefore it is a safe function unlike 'tail' from the standard Prelude+...+>>> tail (Just 'a')+...+... 'tail' works with 'NonEmpty Char' lists+      But given: Maybe Char+...+-}+tail :: IsNonEmpty f a [a] "tail" => f a -> [a]+tail = NE.tail+{-# INLINE tail #-}
src/Relude/List/Reexport.hs view
@@ -1,238 +1,47 @@-{-# LANGUAGE ConstraintKinds      #-}-{-# LANGUAGE DataKinds            #-}-{-# LANGUAGE KindSignatures       #-}-{-# LANGUAGE Trustworthy          #-}-{-# LANGUAGE TypeFamilies         #-}-{-# LANGUAGE TypeOperators        #-}-{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE Trustworthy #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>--Reexports most of the "Data.List" and "Data.List.NonEmpty".--Note, that Relude reexports 'head', 'tail', 'init', 'last' from-"Data,List.NonEmpty" instead of the "Data.List", so these functions are safe to-use.+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -@relude@ also provides custom type error for better experience with transition-from lists to 'NonEmpty' with those functions.+Reexports most of the "Data.List". -}  module Relude.List.Reexport-       ( -- * List-         module Data.List-       , sortWith-         -- * NonEmpty List-       , NonEmpty (..)-       , nonEmpty-       , head-       , init-       , last-       , tail-       ) where+    ( -- * List+      module Data.List+    , cycle+    , sortWith+    ) where -import Data.List (break, cycle, drop, dropWhile, filter, genericDrop, genericLength,-                  genericReplicate, genericSplitAt, genericTake, group, inits, intercalate,-                  intersperse, isPrefixOf, iterate, map, permutations, repeat, replicate, reverse,-                  scanl, scanr, sort, sortBy, sortOn, splitAt, subsequences, tails, take, takeWhile,-                  transpose, uncons, unfoldr, unzip, unzip3, zip, zip3, zipWith, (++))-import Data.List.NonEmpty (NonEmpty (..), nonEmpty)+import Data.List (break, drop, dropWhile, filter, genericDrop, genericLength, genericReplicate,+                  genericSplitAt, genericTake, group, inits, intercalate, intersperse, isPrefixOf,+                  iterate, map, permutations, repeat, replicate, reverse, scanl, scanl', scanl1,+                  scanr, scanr1, sort, sortBy, sortOn, splitAt, subsequences, tails, take,+                  takeWhile, transpose, uncons, unfoldr, unzip, unzip3, zip, zip3, zipWith, (++)) import GHC.Exts (sortWith)-import GHC.TypeLits (ErrorMessage (..), Symbol, TypeError) -import Relude.Base (Constraint, Type) -import qualified Data.List.NonEmpty as NE (head, init, last, tail)-- -- $setup -- >>> import Relude ---- | For tracking usage of ordinary list with @head@-like functions.-type IsNonEmpty-    (f :: Type -> Type)  -- Container, e.g. NonEmpty or []-    (a :: Type)          -- Type of the element-    (res :: Type)        -- Type of the result of the work of the function-    (fun :: Symbol)      -- Function name-    = (f ~ NonEmpty, CheckNonEmpty f a res fun)--type family CheckNonEmpty-    (f :: Type -> Type)-    (a :: Type)-    (res :: Type)-    (fun :: Symbol)-    :: Constraint-  where-    CheckNonEmpty NonEmpty _ _ _ = ()-    CheckNonEmpty [] a res fun = TypeError-        ( 'Text "'" ':<>: 'Text fun ':<>: 'Text "' works with 'NonEmpty', not ordinary lists."-        ':$$: 'Text "Possible fix:"-        ':$$: 'Text "    Replace: [" ':<>: 'ShowType a ':<>: 'Text "]"-        ':$$: 'Text "    With:    NonEmpty " ':<>: 'ShowType a-        ':$$: 'Text ""-        ':$$: 'Text "However, you can use '" ':<>: 'Text fun ':<>: 'Text "' with the ordinary lists."-        ':$$: 'Text "Apply 'viaNonEmpty' function from relude:"-        ':$$: 'Text "    viaNonEmpty " ':<>: 'Text fun ':<>: 'Text " (yourList)"-        ':$$: 'Text "Note, that this will return 'Maybe " ':<>: 'ShowType res ':<>: 'Text "'"-        ':$$: 'Text "therefore it is a safe function unlike '" ':<>: 'Text fun ':<>: 'Text "' from the standard Prelude"-        )-    CheckNonEmpty t a _ fun = TypeError-        ( 'Text "'"-        ':<>: 'Text fun-        ':<>: 'Text "' works with 'NonEmpty "-        ':<>: 'ShowType a-        ':<>: 'Text "' lists"-        ':$$: 'Text "But given: "-        ':<>: 'ShowType t-        ':<>: 'Text " "-        ':<>: 'ShowType a-        )---{- | @O(1)@. Extracts the first element of a 'NonEmpty' list.--Actual type of this function is the following:--@-head :: 'NonEmpty' a -> a-@--but it was given a more complex type to provide friendlier compile time errors.-->>> head ('a' :| "bcde")-'a'->>> head [0..5 :: Int]-...-... 'head' works with 'NonEmpty', not ordinary lists.-      Possible fix:-          Replace: [Int]-          With:    NonEmpty Int-...-      However, you can use 'head' with the ordinary lists.-      Apply 'viaNonEmpty' function from relude:-          viaNonEmpty head (yourList)-      Note, that this will return 'Maybe Int'-      therefore it is a safe function unlike 'head' from the standard Prelude-...->>> head (Just 'a')-...-... 'head' works with 'NonEmpty Char' lists-      But given: Maybe Char-...--}-head :: IsNonEmpty f a a "head" => f a -> a-head = NE.head-{-# INLINE head #-}--{- | @O(n)@. Return all the elements of a 'NonEmpty' list except the last one-element.--Actual type of this function is the following:--@-init :: 'NonEmpty' a -> [a]-@--but it was given a more complex type to provide friendlier compile time errors.-->>> init ('a' :| "bcde")-"abcd"->>> init [0..5 :: Int]-...-... 'init' works with 'NonEmpty', not ordinary lists.-      Possible fix:-          Replace: [Int]-          With:    NonEmpty Int-...-      However, you can use 'init' with the ordinary lists.-      Apply 'viaNonEmpty' function from relude:-          viaNonEmpty init (yourList)-      Note, that this will return 'Maybe [Int]'-      therefore it is a safe function unlike 'init' from the standard Prelude-...->>> init (Just 'a')-...-... 'init' works with 'NonEmpty Char' lists-      But given: Maybe Char-...--}-init :: IsNonEmpty f a [a] "init" => f a -> [a]-init = NE.init-{-# INLINE init #-}--{- | @O(n)@. Extracts the last element of a 'NonEmpty' list.--Actual type of this function is the following:--@-last :: 'NonEmpty' a -> a-@--but it was given a more complex type to provide friendlier compile time errors.-->>> last ('a' :| "bcde")-'e'->>> last [0..5 :: Int]-...-... 'last' works with 'NonEmpty', not ordinary lists.-      Possible fix:-          Replace: [Int]-          With:    NonEmpty Int-...-      However, you can use 'last' with the ordinary lists.-      Apply 'viaNonEmpty' function from relude:-          viaNonEmpty last (yourList)-      Note, that this will return 'Maybe Int'-      therefore it is a safe function unlike 'last' from the standard Prelude-...->>> last (Just 'a')-...-... 'last' works with 'NonEmpty Char' lists-      But given: Maybe Char-...--}-last :: IsNonEmpty f a a "last" => f a -> a-last = NE.last-{-# INLINE last #-}--{- | @O(1)@. Return all the elements of a 'NonEmpty' list after the head-element.--Actual type of this function is the following:--@-tail :: 'NonEmpty' a -> [a]-@--but it was given a more complex type to provide friendlier compile time errors.+{- | Creates an infinite list from a finite list by appending the list+to itself infinite times (i.e. by cycling the list). Unlike @cycle@+from "Data.List", this implementation doesn't throw error on empty+lists, but returns an empty list instead. ->>> tail ('a' :| "bcde")-"bcde"->>> tail [0..5 :: Int]-...-... 'tail' works with 'NonEmpty', not ordinary lists.-      Possible fix:-          Replace: [Int]-          With:    NonEmpty Int-...-      However, you can use 'tail' with the ordinary lists.-      Apply 'viaNonEmpty' function from relude:-          viaNonEmpty tail (yourList)-      Note, that this will return 'Maybe [Int]'-      therefore it is a safe function unlike 'tail' from the standard Prelude-...->>> tail (Just 'a')-...-... 'tail' works with 'NonEmpty Char' lists-      But given: Maybe Char-...+>>> cycle []+[]+>>> take 10 $ cycle [1,2,3]+[1,2,3,1,2,3,1,2,3,1] -}-tail :: IsNonEmpty f a [a] "tail" => f a -> [a]-tail = NE.tail-{-# INLINE tail #-}+cycle :: [a] -> [a]+cycle [] = []+cycle xs = cycledList+  where+    cycledList = xs ++ cycledList
src/Relude/Monad.hs view
@@ -3,26 +3,33 @@ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Reexporting useful monadic stuff. -}  module Relude.Monad-       ( module Relude.Monad.Either-       , module Relude.Monad.Maybe-       , module Relude.Monad.Reexport-       , module Relude.Monad.Trans-       , chainedTo-       ) where+    ( module Relude.Monad.Reexport+      -- $reexport+    , module Relude.Monad.Maybe+      -- $maybe+    , module Relude.Monad.Either+      -- $either+    , module Relude.Monad.Trans+      -- $trans+    , chainedTo+    ) where  import Relude.Monad.Either import Relude.Monad.Maybe import Relude.Monad.Reexport import Relude.Monad.Trans + -- $setup -- >>> import Relude @@ -33,7 +40,22 @@ Just 1 >>> Nothing & chainedTo (viaNonEmpty head) Nothing++@since 0.5.0 -} chainedTo :: Monad m => (a -> m b) -> m a -> m b chainedTo = (=<<) {-# INLINE chainedTo #-}++{- $reexport+Reexports functions to work with different monads.+-}+{- $maybe+Provided new combinators to work with 'Relude.Maybe' data type.+-}+{- $either+Provided new combinators to work with 'Relude.Either' data type.+-}+{- $trans+Monad transformers functions and combinators.+-}
src/Relude/Monad/Either.hs view
@@ -1,35 +1,40 @@+{-# OPTIONS_GHC -fno-warn-orphans #-}+ {-# LANGUAGE CPP  #-} {-# LANGUAGE Safe #-} -{-# OPTIONS_GHC -fno-warn-orphans #-}- {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Utilites to work with @Either@ data type.+Utilities to work with 'Relude.Either' data type. -}  module Relude.Monad.Either-       ( fromLeft-       , fromRight-       , maybeToLeft-       , maybeToRight-       , leftToMaybe-       , rightToMaybe-       , whenLeft-       , whenLeft_-       , whenLeftM-       , whenLeftM_-       , whenRight-       , whenRight_-       , whenRightM-       , whenRightM_-       ) where+    ( -- * Combinators+      fromLeft+    , fromRight+    , maybeToLeft+    , maybeToRight+    , leftToMaybe+    , rightToMaybe+    , whenLeft+    , whenLeft_ +      -- * Monadic combinators+    , whenLeftM+    , whenLeftM_+    , whenRight+    , whenRight_+    , whenRightM+    , whenRightM_+    ) where+ import Control.Applicative (Applicative) import Control.Monad (Monad (..)) import Data.Function (const)@@ -43,6 +48,8 @@ #if MIN_VERSION_base(4,10,0) import Data.Either (fromLeft, fromRight) #else++ -- | Extracts value from 'Left' or return given default value. -- -- >>> fromLeft 0 (Left 3)@@ -68,9 +75,14 @@ -- $setup -- >>> import Relude +{- | For convenient work with 'MonadFail'.++@since 0.1.0+-} instance IsString str => MonadFail (Either str) where     fail :: String -> Either str a     fail = Left . fromString+    {-# INLINE fail #-}  {- | Maps left part of 'Either' to 'Maybe'. 
src/Relude/Monad/Maybe.hs view
@@ -3,23 +3,27 @@ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Utility functions to work with 'Data.Maybe' data type as monad.+Utility functions to work with 'Relude.Maybe' data type as monad. -}  module Relude.Monad.Maybe-       ( (?:)-       , whenJust-       , whenJustM-       , whenNothing-       , whenNothing_-       , whenNothingM-       , whenNothingM_-       , mapMaybeM-       ) where+    ( -- * Combinators+      (?:)+    , whenJust+    , whenJustM+    , whenNothing+    , whenNothing_+      -- * Monadic combinators+    , whenNothingM+    , whenNothingM_+    , mapMaybeM+    ) where  import Relude.Applicative (Applicative, pass, pure) import Relude.Foldable.Reexport (mapM)
src/Relude/Monad/Reexport.hs view
@@ -3,32 +3,34 @@ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Reexports functions to work with monads. -}  module Relude.Monad.Reexport-       ( -- * Reexport transformers-         module Control.Monad.Except-       , module Control.Monad.Reader-       , module Control.Monad.State.Strict-       , module Control.Monad.Trans-       , module Control.Monad.Trans.Identity-       , module Control.Monad.Trans.Maybe+    ( -- * Reexport transformers+      module Control.Monad.Except+    , module Control.Monad.Reader+    , module Control.Monad.State.Strict+    , module Control.Monad.Trans+    , module Control.Monad.Trans.Identity+    , module Control.Monad.Trans.Maybe -         -- * Reexport monadic functions-       , module Control.Monad-       , module Control.Monad.Fail+      -- * Reexport monadic functions+    , module Control.Monad+    , module Control.Monad.Fail -         -- * Reexport 'Maybe'-       , module Data.Maybe+      -- * Reexport 'Maybe'+    , module Data.Maybe -         -- * Reexport 'Either'-       , module Data.Either-       ) where+      -- * Reexport 'Either'+    , module Data.Either+    ) where  -- Monad transformers import Control.Monad.Except (ExceptT (..), runExceptT)
src/Relude/Monad/Trans.hs view
@@ -1,37 +1,49 @@-{-# LANGUAGE Safe #-}+{-# LANGUAGE CPP         #-}+{-# LANGUAGE Trustworthy #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Monad transformers utilities. -}  module Relude.Monad.Trans-       ( -- * Convenient functions to work with 'Reader' monad-         usingReader-       , usingReaderT+    ( -- * Convenient functions to work with 'Reader' monad+      usingReader+    , usingReaderT -         -- * Convenient functions to work with 'State' monad-       , evaluatingState-       , evaluatingStateT-       , executingState-       , executingStateT-       , usingState-       , usingStateT-         -- * Lifted to Transformers-       , hoistMaybe-       , hoistEither-       ) where+#if MIN_VERSION_base(4,10,0)+    , etaReaderT+#endif -import Prelude (flip, fst, snd)+      -- * Convenient functions to work with 'State' monad+    , evaluatingState+    , evaluatingStateT+    , executingState+    , executingStateT+    , usingState+    , usingStateT +      -- * Lifted to Transformers+    , hoistMaybe+    , hoistEither+    ) where++#if MIN_VERSION_base(4,10,0)+import GHC.Exts (oneShot)+#endif+ import Relude.Applicative (Applicative (pure))+import Relude.Container.Reexport (fst, snd)+import Relude.Function (flip, (.)) import Relude.Functor (Functor, (<$>))-import Relude.Monad.Reexport (Either, ExceptT (..), Maybe, MaybeT (..), Reader, ReaderT, State,+import Relude.Monad.Reexport (Either, ExceptT (..), Maybe, MaybeT (..), Reader, ReaderT (..), State,                               StateT, runReader, runReaderT, runState, runStateT)  @@ -56,6 +68,39 @@ usingReader = flip runReader {-# INLINE usingReader #-} +#if MIN_VERSION_base(4,10,0)+{- | This function helps with optimizing performance when working with+the 'ReaderT' transformer. If you have code like below, that is+called in a loop++@+step :: Instruction -> 'ReaderT' Config IO Result+step instruction = __case__ instruction __of__+    Add -> __do__ stuff ...+    Del -> __do__ stuff ...+@++you can improve performance of your Haskell applications by using+'etaReaderT' in the following way:++@+step :: Instruction -> 'ReaderT' Config IO Result+step instruction = 'etaReaderT' $ __case__ instruction __of__+    Add -> __do__ stuff ...+    Del -> __do__ stuff ...+@++For a detailed explanation, refer to the following blog post:++* <https://www.joachim-breitner.de/blog/763-Faster_Winter_5__Eta-Expanding_ReaderT Faster Winter 5: Eta-Expanding ReaderT (by Joachim Breitners)>++@since 0.7.0.0+-}+etaReaderT :: ReaderT r m a -> ReaderT r m a+etaReaderT = ReaderT . oneShot . runReaderT+{-# INLINE etaReaderT #-}+#endif+ {- | Shorter and more readable alias for @flip runStateT@.  >>> usingStateT 0 $ put 42 >> pure False@@ -98,12 +143,18 @@ executingState s st = snd (usingState s st) {-# INLINE executingState #-} --- | Lift a 'Maybe' to the 'MaybeT' monad+{- | Lift a 'Maybe' to the 'MaybeT' monad++@since 0.3.0+-} hoistMaybe  :: Applicative m => Maybe a -> MaybeT m a hoistMaybe m = MaybeT (pure m) {-# INLINE hoistMaybe #-} --- | Lift a 'Either' to the 'ExceptT' monad+{- | Lift a 'Either' to the 'ExceptT' monad++@since 0.3.0+-} hoistEither :: Applicative m => Either e a -> ExceptT e m a hoistEither e = ExceptT (pure e) {-# INLINE hoistEither #-}
src/Relude/Monoid.hs view
@@ -1,25 +1,37 @@ {-# LANGUAGE CPP                        #-} {-# LANGUAGE DeriveGeneric              #-}+#if !MIN_VERSION_base(4,12,0) {-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE Trustworthy                #-}+#else+{-# LANGUAGE Safe                       #-}+#endif  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Reexports functions to work with monoids plus adds extra useful functions. -}  module Relude.Monoid-       ( module Data.Monoid-       , module Data.Semigroup+    ( -- * Reexports+      module Data.Monoid+    , module Data.Semigroup -       , Ap (..)-       , maybeToMonoid-       ) where+    , Ap (..) +      -- * Combinators+    , maybeToMonoid+    , memptyIfFalse+    , memptyIfTrue+    ) where+ #if MIN_VERSION_base(4,12,0) import Data.Monoid (Ap (..)) #endif@@ -28,6 +40,7 @@ import Data.Semigroup (Option (..), Semigroup (sconcat, stimes, (<>)), WrappedMonoid, cycle1,                        mtimesDefault, stimesIdempotent, stimesIdempotentMonoid, stimesMonoid) +import Relude.Bool.Reexport (Bool (..)) import Relude.Monad.Reexport (Maybe, fromMaybe)  #if !MIN_VERSION_base(4,12,0)@@ -57,6 +70,35 @@ maybeToMonoid :: Monoid m => Maybe m -> m maybeToMonoid = fromMaybe mempty {-# INLINE maybeToMonoid #-}++{- | Returns the given value in case of the given predicate is satisfied+(is 'True'). Otherwise, it returns 'mempty'.++>>> memptyIfFalse True (Just "Hello")+Just "Hello"+>>> memptyIfFalse False "Doesn't matter"+""++@since 0.7.0.0+-}+memptyIfFalse :: Monoid m => Bool -> m -> m+memptyIfFalse p val = if p then val else mempty+{-# INLINE memptyIfFalse #-}+++{- | Returns the given value in case of the given predicate is unsatisfied+(is 'False'). Otherwise, it returns 'mempty'.++>>> memptyIfTrue True (Just "Hello")+Nothing+>>> memptyIfTrue False "Does matter"+"Does matter"++@since 0.7.0.0+-}+memptyIfTrue :: Monoid m => Bool -> m -> m+memptyIfTrue p val = if p then mempty else val+{-# INLINE memptyIfTrue #-}  #if !MIN_VERSION_base(4,12,0) -- | This data type witnesses the lifting of a 'Monoid' into an
src/Relude/Nub.hs view
@@ -1,9 +1,13 @@+{-# LANGUAGE Safe #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Functions to remove duplicates from a list. @@ -17,7 +21,7 @@  * Lists which consist of many same elements  - Here are some recomendations for usage of particular functions based on benchmarking resutls.+ Here are some recommendations for usage of particular functions based on benchmarking results.   * 'hashNub' is faster than 'ordNub' when there're not so many different values in the list. @@ -29,11 +33,11 @@ -}  module Relude.Nub-       ( hashNub-       , ordNub-       , sortNub-       , unstableNub-       ) where+    ( hashNub+    , ordNub+    , sortNub+    , unstableNub+    ) where  import Data.Eq (Eq) import Data.Hashable (Hashable)
src/Relude/Numeric.hs view
@@ -1,21 +1,31 @@+{-# LANGUAGE Trustworthy #-}+ {- |-Copyright:  (c) 2018-2019 Kowainik+Copyright:  (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable++Provides numerical data types and functions.++@since 0.5.0 -}  module Relude.Numeric-       ( module Data.Bits-       , module Data.Int-       , module Data.Word-       , module GHC.Base-       , module GHC.Float-       , module GHC.Num-       , module GHC.Real-       , module Numeric.Natural-       , integerToBounded-       , integerToNatural-       ) where+    ( -- * Reexports+      module Data.Bits+    , module Data.Int+    , module Data.Word+    , module GHC.Base+    , module GHC.Float+    , module GHC.Num+    , module GHC.Real+    , module Numeric.Natural+      -- * Combinators+    , integerToBounded+    , integerToNatural+    ) where  import Data.Bits (toIntegralSized, xor) import Data.Int (Int, Int16, Int32, Int64, Int8)@@ -46,6 +56,7 @@ >>> integerToBounded @Int8 1024 Nothing +@since 0.5.0 -} integerToBounded :: forall a. (Integral a, Bounded a) => Integer -> Maybe a integerToBounded n@@ -54,7 +65,7 @@     | otherwise                   = Just (fromIntegral n) {-# INLINE integerToBounded #-} -{- | Tranforms an integer number to a natural.+{- | Transforms an integer number to a natural. Only non-negative integers are considered natural, everything else will return `Nothing`.  >>> integerToNatural (-1)@@ -66,6 +77,7 @@ >>> integerToNatural 10 Just 10 +@since 0.5.0 -} integerToNatural :: Integer -> Maybe Natural integerToNatural n
src/Relude/Print.hs view
@@ -1,32 +1,34 @@ {-# LANGUAGE ExplicitForAll    #-} {-# LANGUAGE FlexibleContexts  #-} {-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE Trustworthy       #-}+{-# LANGUAGE Safe              #-}  {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Functions like 'Prelude.putStr' and 'Prelude.putStrLn' but for 'Text', 'LText', 'ByteString' and 'LByteString'. -}  module Relude.Print-       ( -- * 'Text' & 'LText'-         putText-       , putTextLn-       , putLText-       , putLTextLn+    ( -- * 'Text' & 'LText'+      putText+    , putTextLn+    , putLText+    , putLTextLn -         -- * 'ByteString' & 'LByteString'-       , putBS-       , putBSLn-       , putLBS-       , putLBSLn-       ) where+      -- * 'ByteString' & 'LByteString'+    , putBS+    , putBSLn+    , putLBS+    , putLBSLn+    ) where  import Relude.Function ((.)) import Relude.Monad.Reexport (MonadIO (..))@@ -91,6 +93,8 @@  >>> putBS ("Hello, world!" :: ByteString) Hello, world!++@since 0.3.0 -} putBS :: MonadIO m => ByteString -> m () putBS = liftIO . BS.putStr@@ -103,6 +107,7 @@ >>> putBSLn ("Hello, world!" :: ByteString) Hello, world! +@since 0.3.0 -} putBSLn :: MonadIO m => ByteString -> m () putBSLn = liftIO . BS.putStrLn@@ -114,6 +119,7 @@ >>> putLBS ("Hello, world!" :: LByteString) Hello, world! +@since 0.3.0 -} putLBS :: MonadIO m => LByteString -> m () putLBS = liftIO . LBS.putStr@@ -125,6 +131,7 @@ >>> putLBSLn ("Hello, world!" :: LByteString) Hello, world! +@since 0.3.0 -} putLBSLn :: MonadIO m => LByteString -> m () putLBSLn = liftIO . LBS.putStrLn
src/Relude/String.hs view
@@ -1,17 +1,59 @@+{-# LANGUAGE Safe #-}+ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Type classes for convertion between different string representations.+Type classes for conversion between different string representations.++The table below represents the @relude@ concept of conversion between the following types:++* 'Text'+* 'String'+* 'ByteString'+* 'LText'+* 'LByteString'+* 'ShortByteString'++++-----------------------+---------------------+--------------+--------------+--------------------+------------------------+--------------------------++|     From \\ To        |       'Text'        |   'String'   | 'ByteString' |      'LText'       |   'LByteString'        |   'ShortByteString'      |++=======================+=====================+==============+==============+====================+========================+==========================++| __'Text'__            | ~                   | 'toString'   | 'encodeUtf8' | 'toLazy'/'toLText' | 'encodeUtf8'           | 'encodeUtf8'             |++-----------------------+---------------------+--------------+--------------+--------------------+------------------------+--------------------------++| __'String'__          | 'toText'            | ~            | 'encodeUtf8' | 'toLText'          | 'encodeUtf8'           | 'encodeUtf8'             |++-----------------------+---------------------+--------------+--------------+--------------------+------------------------+--------------------------++| __'ByteString'__      | 'decodeUtf8'        | 'decodeUtf8' | ~            | 'decodeUtf8'       | 'toLazy'               | 'toShort'                |++-----------------------+---------------------+--------------+--------------+--------------------+------------------------+--------------------------++| __'LText'__           | 'toStrict'/'toText' | 'toString'   | 'encodeUtf8' |  ~                 | 'encodeUtf8'           | 'encodeUtf8'             |++-----------------------+---------------------+--------------+--------------+--------------------+------------------------+--------------------------++| __'LByteString'__     | 'decodeUtf8'        | 'decodeUtf8' | 'toStrict'   | 'decodeUtf8'       | ~                      | @'toShort' . 'toStrict'@ |++-----------------------+---------------------+--------------+--------------+--------------------+------------------------+--------------------------++| __'ShortByteString'__ | 'decodeUtf8'        | 'decodeUtf8' | 'fromShort'  | 'decodeUtf8'       |@'toLazy' . 'fromShort'@| ~                        |++-----------------------+---------------------+--------------+--------------+--------------------+------------------------+--------------------------++ -}  module Relude.String-       ( module Relude.String.Conversion-       , module Relude.String.Reexport-       ) where+    ( module Relude.String.Reexport+      -- $reexport+    , module Relude.String.Conversion+      -- $conversion+    ) where  import Relude.String.Conversion import Relude.String.Reexport++{- $reexport+Reexport data types and functions to work with 'Text', 'ByteString',+'ShortByteString'.+-}+{- $conversion+Conversion functions between 'Text', 'String', 'ByteString'.+Also some read|show helper functions.+-}
src/Relude/String/Conversion.hs view
@@ -3,6 +3,7 @@ {-# LANGUAGE FlexibleInstances      #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses  #-}+{-# LANGUAGE Safe                   #-} {-# LANGUAGE TypeFamilies           #-} {-# LANGUAGE TypeOperators          #-} {-# LANGUAGE TypeSynonymInstances   #-}@@ -11,9 +12,11 @@ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  This module implements type class which allow to have conversion to and from 'Relude.String.Reexport.Text', 'String' and 'ByteString' types@@ -24,23 +27,23 @@ -}  module Relude.String.Conversion-       ( -- * Convenient type aliases-         LText-       , LByteString+    ( -- * Convenient type aliases+      LText+    , LByteString -         -- * Conversion type classes-       , ConvertUtf8 (..)-       , ToText (..)-       , ToLText (..)-       , ToString (..)-       , LazyStrict (..)-       , fromLazy-       , fromStrict+      -- * Conversion type classes+    , ConvertUtf8 (..)+    , ToText (..)+    , ToLText (..)+    , ToString (..)+    , LazyStrict (..)+    , fromLazy+    , fromStrict -         -- * Show and read functions-       , readEither-       , show-       ) where+      -- * Show and read functions+    , readEither+    , show+    ) where  import GHC.TypeLits (ErrorMessage (..), Symbol, TypeError) import Prelude (error)@@ -479,15 +482,16 @@         ':<>: 'Text " -> Either UnicodeException " ':<>: 'Text to         ) -{- | Polymorhpic version of 'Text.Read.readEither'.+{- | Version of 'Text.Read.readEither' that returns 'Text' in case of the parse+error. ->>> readEither @Text @Int "123"+>>> readEither @Int "123" Right 123->>> readEither @Text @Int "aa"+>>> readEither @Int "aa" Left "Prelude.read: no parse" -}-readEither :: (ToString a, Read b) => a -> Either Text b-readEither = first toText . Text.Read.readEither . toString+readEither :: (Read a) => String -> Either Text a+readEither = first toText . Text.Read.readEither {-# INLINEABLE readEither #-}  {- | Generalized version of 'Prelude.show'. Unlike 'Prelude.show' this function@@ -513,7 +517,10 @@ {-# SPECIALIZE show :: Show.Show  a => a -> LByteString  #-} {-# SPECIALIZE show :: Show.Show  a => a -> String  #-} --- | Type class for lazy-strict conversions.+{- | Type class for lazy-strict conversions.++@since 0.1.0+-} class LazyStrict l s | l -> s, s -> l where     toLazy   :: s -> l     toStrict :: l -> s
src/Relude/String/Reexport.hs view
@@ -1,7 +1,7 @@ {-# LANGUAGE ConstraintKinds      #-} {-# LANGUAGE DataKinds            #-} {-# LANGUAGE KindSignatures       #-}-{-# LANGUAGE Trustworthy          #-}+{-# LANGUAGE Safe                 #-} {-# LANGUAGE TypeFamilies         #-} {-# LANGUAGE TypeOperators        #-} {-# LANGUAGE UndecidableInstances #-}@@ -9,36 +9,38 @@ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable  Reexports functions to work with 'Data.Text.Text', 'ByteString' and 'ShortByteString' types. -}  module Relude.String.Reexport-       ( -- * String-         module Data.String-       , module Text.Read+    ( -- * String+      module Data.String+    , module Text.Read -         -- * Text-       , Text-       , lines-       , unlines-       , words-       , unwords-       , module Data.Text.Encoding-       , module Data.Text.Encoding.Error+      -- * Text+    , Text+    , lines+    , unlines+    , words+    , unwords+    , module Data.Text.Encoding+    , module Data.Text.Encoding.Error -         -- * ByteString-       , ByteString+      -- * ByteString+    , ByteString -         -- * ShortByteString-       , ShortByteString-       , toShort-       , fromShort-       ) where+      -- * ShortByteString+    , ShortByteString+    , toShort+    , fromShort+    ) where  import Data.ByteString (ByteString) import Data.ByteString.Short (ShortByteString, fromShort, toShort)
src/Relude/Unsafe.hs view
@@ -3,30 +3,57 @@ {- | Copyright:  (c) 2016 Stephen Diehl             (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik+            (c) 2018-2020 Kowainik SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>+Maintainer:  Kowainik <xrom.xkov@gmail.com>+Stability:   Stable+Portability: Portable -Unsafe functions to work with lists and 'Relude.Maybe'. Sometimes unavoidable but it's-better not to use them. This module is intended to be imported qualified and-it's not even included in default prelude exports.+__⚠️ Warning ⚠️__ +This module contains unsafe partial functions. They are unavoidable+sometimes, but we encourage you to use safer analogues:+++-----------------------------------+---------------------------------------------------------------------++| __Partial__                       | __Total__                                                           |++===================================+=====================================================================++| @'head' :: [a] -> a@              | @'Relude.head' :: NonEmpty a -> a@                                  |++-----------------------------------+---------------------------------------------------------------------++| @'tail' :: [a] -> [a]@            | @'Relude.tail' :: NonEmpty a -> [a]@                                |++-----------------------------------+---------------------------------------------------------------------++| @'read' :: Read a => String -> a@ | @'Relude.String.Reexport.readMaybe' :: Read a => String -> Maybe a@ |++-----------------------------------+---------------------------------------------------------------------++| @'fromJust' :: Maybe a -> a@      | @'Relude.Monad.Reexport.fromMaybe' :: a -> Maybe a -> a@            |++-----------------------------------+---------------------------------------------------------------------+++This module is intended to be imported qualified and it is not+included in default prelude exports.+ @ __import qualified__ Relude.Unsafe as Unsafe  foo :: [a] -> a-foo = Unsafe.head+foo = Unsafe.'head' @ -}  module Relude.Unsafe-       ( module Data.List-       , module Data.Maybe-       , at-       ) where+    ( -- * Unsafe list functions+      head+    , tail+    , last+    , init+    , (!!)+    , at+      -- * Unsafe 'Data.Maybe.Maybe' functions+    , fromJust+      -- * Unsafe "Text.Read" functions+    , read+    ) where  import Data.List (head, init, last, tail, (!!)) import Data.Maybe (fromJust)+import Text.Read (read)  import Relude.Function (flip) import Relude.Numeric (Int)@@ -41,7 +68,7 @@ >>> at 2 ["a", "b", "c"] "c" -it is also usefull when used in a partially applied position like:+it is also useful when used in a partially applied position like:  >>> map (at 1) [["a","b","c"], ["a","b","c"], ["a","b","c"]] ["b","b","b"]
test/Doctest.hs view
@@ -1,11 +1,3 @@-{--Copyright:  (c) 2016 Stephen Diehl-            (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>--}- module Main (main) where  import Relude
test/Spec.hs view
@@ -1,12 +1,4 @@-{--Copyright:  (c) 2016 Stephen Diehl-            (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>--}--module Main where+module Main (main) where  import Relude @@ -14,12 +6,14 @@ import System.IO (hSetEncoding, utf8) import Test.Relude.Property (hedgehogTestList) + main :: IO () main = do   -- fix terminal encoding   hSetEncoding stdout utf8   hSetEncoding stderr utf8 -  mapM checkParallel hedgehogTestList >>= \p -> if and p then exitSuccess else exitFailure-- +  mapM checkParallel hedgehogTestList >>= \p ->+      if and p+      then exitSuccess+      else exitFailure
+ test/Test/Relude/Container/One.hs view
@@ -0,0 +1,114 @@+module Test.Relude.Container.One+    ( oneProps+    ) where++import Relude++import Hedgehog (Gen, Group (..), Property, forAll, property, (===))++import Test.Relude.Gen (genInt, genUtf8Text)++import qualified Data.ByteString as BS+import qualified Data.ByteString.Lazy as LBS+import qualified Data.ByteString.Short as SBS+import qualified Data.IntSet as IntSet+import qualified Data.Text as T+import qualified Data.Text.Lazy as TL+import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+++oneProps :: Group+oneProps = Group "'One' typeclass property tests"+    [ ( "length (one @[a] x)             ≡ 1", oneListProp)+    , ( "length (one @(NonEmpty a) x)    ≡ 1", oneNonEmptyProp)+    , ( "length (one @(Seq a) x)         ≡ 1", oneSeqProp)+    , ( "length (one @Text x)            ≡ 1", oneTextProp)+    , ( "length (one @LText x)           ≡ 1", oneLTextProp)+    , ( "length (one @ByteString x)      ≡ 1", oneByteStringProp)+    , ( "length (one @LByteString x)     ≡ 1", oneLByteStringProp)+    , ( "length (one @ShortByteString x) ≡ 1", oneShortByteStringProp)+    , ( "length (one @(Map k v) x)       ≡ 1", oneMapProp)+    , ( "length (one @(HashMap k v) x)   ≡ 1", oneHashMapProp)+    , ( "length (one @(IntMap v) x)      ≡ 1", oneIntMapProp)+    , ( "length (one @(Set a) x)         ≡ 1", oneSetProp)+    , ( "length (one @(HashSet a) x)     ≡ 1", oneHashSetProp)+    , ( "length (one @(IntSet x)         ≡ 1", oneIntSetProp)+    ]++oneListProp :: Property+oneListProp = property $ do+    x <- forAll genInt+    length (one @[Int] x) === 1++oneNonEmptyProp :: Property+oneNonEmptyProp = property $ do+    x <- forAll genInt+    length (one @(NonEmpty Int) x) === 1++oneSeqProp :: Property+oneSeqProp = property $ do+    x <- forAll genInt+    length (one @(Seq Int) x) === 1++oneTextProp :: Property+oneTextProp = property $ do+    x <- forAll Gen.unicode+    T.length (one @Text x) === 1++oneLTextProp :: Property+oneLTextProp = property $ do+    x <- forAll Gen.unicode+    TL.length (one @LText x) === 1++oneByteStringProp :: Property+oneByteStringProp = property $ do+    x <- forAll genWord8+    BS.length (one @ByteString x) === 1++oneLByteStringProp :: Property+oneLByteStringProp = property $ do+    x <- forAll genWord8+    LBS.length (one @LByteString x) === 1++oneShortByteStringProp :: Property+oneShortByteStringProp = property $ do+    x <- forAll genWord8+    SBS.length (one @ShortByteString x) === 1++oneMapProp :: Property+oneMapProp = property $ do+    k <- forAll genUtf8Text+    v <- forAll genInt+    length (one @(Map Text Int) (k, v)) === 1++oneHashMapProp :: Property+oneHashMapProp = property $ do+    k <- forAll genUtf8Text+    v <- forAll genInt+    length (one @(HashMap Text Int) (k, v)) === 1++oneIntMapProp :: Property+oneIntMapProp = property $ do+    k <- forAll genInt+    v <- forAll genUtf8Text+    length (one @(IntMap Text) (k, v)) === 1++oneSetProp :: Property+oneSetProp = property $ do+    v <- forAll genUtf8Text+    length (one @(Set Text) v) === 1++oneHashSetProp :: Property+oneHashSetProp = property $ do+    v <- forAll genUtf8Text+    length (one @(HashSet Text) v) === 1++oneIntSetProp :: Property+oneIntSetProp = property $ do+    v <- forAll genInt+    IntSet.size (one v) === 1+++genWord8 :: Gen Word8+genWord8 = Gen.word8 Range.constantBounded
test/Test/Relude/Extra/Validation/Property.hs view
@@ -4,12 +4,6 @@ {- HLINT ignore "Monoid law, left identity" -} {- HLINT ignore "Use <$>" -} -{--Copyright:  (c) 2018-2019 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>--}- module Test.Relude.Extra.Validation.Property        ( validationLaws        ) where@@ -53,9 +47,9 @@ -- Property helpers ---------------------------------------------------------------------------- -checkAssotiativityFor+checkAssociativityFor     :: (Show a, Eq a) => Gen a -> (a -> a -> a) -> Property-checkAssotiativityFor gen op = property $ do+checkAssociativityFor gen op = property $ do     a <- forAll gen     b <- forAll gen     c <- forAll gen@@ -73,7 +67,7 @@  prop_semigroupAssociativity :: Property prop_semigroupAssociativity =-    checkAssotiativityFor (asValidation genSmallText) (<>)+    checkAssociativityFor (asValidation genSmallText) (<>)  ---------------------------------------------------------------------------- -- Monoid instance properties@@ -161,7 +155,7 @@  prop_alternativeAssociativity :: Property prop_alternativeAssociativity =-    checkAssotiativityFor (asValidation genSmallText) (<|>)+    checkAssociativityFor (asValidation genSmallText) (<|>)  prop_alternativeRightIdentity :: Property prop_alternativeRightIdentity = property $ do
+ test/Test/Relude/Gen.hs view
@@ -0,0 +1,36 @@+module Test.Relude.Gen+    ( genInt+      -- * Strings+    , genUtf8String+    , genUtf8Text+    , genUtf8ByteString+      -- * Lists+    , genIntList+    , genBoolList+    ) where++import Relude++import Hedgehog (Gen)++import qualified Hedgehog.Gen as Gen+import qualified Hedgehog.Range as Range+++genInt :: Gen Int+genInt = Gen.enumBounded++genUtf8String :: Gen String+genUtf8String = Gen.string (Range.linear 0 1000) Gen.unicode++genUtf8Text :: Gen Text+genUtf8Text = Gen.text (Range.linear 0 1000) Gen.unicode++genUtf8ByteString :: Gen ByteString+genUtf8ByteString = Gen.utf8 (Range.linear 0 1000) Gen.unicode++genIntList :: Gen [Int]+genIntList = Gen.list (Range.linear 0 1000) Gen.enumBounded++genBoolList :: Gen [Bool]+genBoolList = Gen.list (Range.linear 0 1000) Gen.bool
test/Test/Relude/Property.hs view
@@ -1,29 +1,23 @@-{--Copyright:  (c) 2016 Stephen Diehl-            (c) 2016-2018 Serokell-            (c) 2018-2019 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>--}- module Test.Relude.Property        ( hedgehogTestList        ) where  import Relude-import Test.Relude.Extra.Validation.Property (validationLaws)  import Data.List (nub)-import Hedgehog (Gen, Property, Group (..), assert, forAll, property, (===))+import Hedgehog (Group (..), Property, assert, forAll, property, (===)) -import qualified Hedgehog.Gen as Gen-import qualified Hedgehog.Range as Range+import Test.Relude.Container.One (oneProps)+import Test.Relude.Extra.Validation.Property (validationLaws)+import Test.Relude.Gen (genBoolList, genIntList, genUtf8ByteString, genUtf8String, genUtf8Text) + hedgehogTestList :: [Group] hedgehogTestList =     [ utfProps     , listProps     , logicProps+    , oneProps     ] <> validationLaws  ----------------------------------------------------------------------------@@ -36,37 +30,28 @@     , ("Text to ByteString invertible:", prop_TextToBytes)     , ("ByteString to Text or String invertible:" , prop_BytesTo)     ]-      -utf8String :: Gen String-utf8String = Gen.string (Range.linear 0 1000) Gen.unicode -utf8Text :: Gen Text-utf8Text = Gen.text (Range.linear 0 1000) Gen.unicode--utf8Bytes :: Gen ByteString-utf8Bytes = Gen.utf8 (Range.linear 0 1000) Gen.unicode- -- "\65534" fails, but this is from BU.toString -- > import qualified Data.ByteString.UTF8 as BU -- > BU.toString (BU.fromString "\65534") == "\65533" -- > True prop_StringToBytes :: Property prop_StringToBytes = property $ do-    str <- forAll utf8String+    str <- forAll genUtf8String     assert $ str == decodeUtf8 @_ @ByteString  (encodeUtf8 str)           && str == decodeUtf8 @_ @LByteString (encodeUtf8 str)   prop_TextToBytes :: Property prop_TextToBytes = property $ do-    txt <- forAll utf8Text+    txt <- forAll genUtf8Text     assert $ txt == decodeUtf8 @_ @ByteString  (encodeUtf8 txt)           && txt == decodeUtf8 @_ @LByteString (encodeUtf8 txt)  -- "\239\191\190" fails, but this is the same as "\65534" :: String prop_BytesTo :: Property prop_BytesTo = property $ do-    utf <- forAll utf8Bytes+    utf <- forAll genUtf8ByteString     assert $ utf == encodeUtf8 @String (decodeUtf8 utf)           && utf == encodeUtf8 @Text   (decodeUtf8 utf)           && utf == encodeUtf8 @LText  (decodeUtf8 utf)@@ -82,9 +67,6 @@     , ("sortNub xs == sort (nub xs):" , prop_sortNubCorrect)     , ("sort (unstableNub xs) == sort (nub xs):" , prop_unstableNubCorrect)     ]-      -genIntList :: Gen [Int]-genIntList = Gen.list (Range.linear 0 1000) Gen.enumBounded  prop_ordNubCorrect :: Property prop_ordNubCorrect = property $ do@@ -115,9 +97,6 @@     [ ("andM:", prop_andM)     , ("orM:", prop_orM)     ]-      -genBoolList :: Gen [Bool]-genBoolList = Gen.list (Range.linear 0 1000) Gen.bool  prop_andM :: Property prop_andM = property $ do