relude 0.7.0.0 → 1.2.2.2
raw patch · 65 files changed
Files
- CHANGELOG.md +332/−146
- README.md +250/−189
- benchmark/Main.hs +36/−2
- relude.cabal +96/−58
- src/Relude.hs +18/−15
- src/Relude/Applicative.hs +24/−17
- src/Relude/Base.hs +19/−22
- src/Relude/Bool.hs +8/−7
- src/Relude/Bool/Guard.hs +34/−12
- src/Relude/Bool/Reexport.hs +8/−7
- src/Relude/Container.hs +8/−7
- src/Relude/Container/One.hs +22/−19
- src/Relude/Container/Reexport.hs +8/−7
- src/Relude/Debug.hs +107/−46
- src/Relude/DeepSeq.hs +11/−10
- src/Relude/Enum.hs +149/−0
- src/Relude/Exception.hs +12/−18
- src/Relude/Extra.hs +14/−23
- src/Relude/Extra/Bifunctor.hs +6/−5
- src/Relude/Extra/CallStack.hs +6/−5
- src/Relude/Extra/Enum.hs +9/−122
- src/Relude/Extra/Foldable.hs +33/−5
- src/Relude/Extra/Foldable1.hs +141/−10
- src/Relude/Extra/Group.hs +9/−7
- src/Relude/Extra/Lens.hs +37/−7
- src/Relude/Extra/Map.hs +30/−7
- src/Relude/Extra/Newtype.hs +6/−10
- src/Relude/Extra/Tuple.hs +14/−8
- src/Relude/Extra/Type.hs +25/−15
- src/Relude/Extra/Validation.hs +0/−432
- src/Relude/File.hs +17/−5
- src/Relude/Foldable.hs +6/−5
- src/Relude/Foldable/Fold.hs +23/−12
- src/Relude/Foldable/Reexport.hs +7/−10
- src/Relude/Function.hs +8/−7
- src/Relude/Functor.hs +8/−7
- src/Relude/Functor/Fmap.hs +14/−8
- src/Relude/Functor/Reexport.hs +13/−9
- src/Relude/Lifted.hs +34/−21
- src/Relude/Lifted/Concurrent.hs +8/−7
- src/Relude/Lifted/Env.hs +44/−0
- src/Relude/Lifted/Exit.hs +8/−7
- src/Relude/Lifted/File.hs +25/−7
- src/Relude/Lifted/Handle.hs +70/−0
- src/Relude/Lifted/IORef.hs +8/−7
- src/Relude/Lifted/Terminal.hs +6/−5
- src/Relude/List.hs +57/−9
- src/Relude/List/NonEmpty.hs +17/−7
- src/Relude/List/Reexport.hs +9/−8
- src/Relude/Monad.hs +38/−9
- src/Relude/Monad/Either.hs +10/−35
- src/Relude/Monad/Maybe.hs +12/−11
- src/Relude/Monad/Reexport.hs +16/−11
- src/Relude/Monad/Trans.hs +9/−16
- src/Relude/Monoid.hs +14/−12
- src/Relude/Nub.hs +91/−9
- src/Relude/Numeric.hs +21/−6
- src/Relude/Print.hs +8/−7
- src/Relude/String.hs +8/−8
- src/Relude/String/Conversion.hs +23/−8
- src/Relude/String/Reexport.hs +17/−7
- src/Relude/Unsafe.hs +10/−9
- test/Doctest.hs +2/−1
- test/Test/Relude/Extra/Validation/Property.hs +0/−168
- test/Test/Relude/Property.hs +1/−2
CHANGELOG.md view
@@ -3,84 +3,263 @@ `relude` uses [PVP Versioning][1]. The changelog is available [on GitHub][2]. +## 1.2.2.2 – Aug 5, 2025 +- Documentation improvements++## 1.2.2.1 – Jul 29, 2025++- Allow containers-0.8.++- Documentation improvements++## 1.2.2.0 – Oct 13, 2024++- Support GHC-9.10 & GHC-9.8.+- Allow hashable-1.5++## 1.2.1.0 – Oct 4, 2023++- [#439](https://github.com/kowainik/relude/issues/439):+ Support GHC-9.6.+- Upgrade dependencies. Allow:+ - `ghc-prim-0.10`+ - `text-2.1`+ - `bytestring-2.12`+ - `containers-0.7`+ - `deepseq-1.5`+ - `hedgehod-1.3`+ - `doctest-0.22`+- Upgrade tests to work with GHC-9.6.++## 1.2.0.0 – Mar 1, 2023++- [#420](https://github.com/kowainik/relude/issues/420):+ Support GHC-9.4.+- Reexport `type (~)` from `Data.Type.Equality` for GHC-9.4.+- Add `-Wredundant-strictness-flags` and `-Wforall-identifier` warnings for+ GHC-9.4.+- [#430](https://github.com/kowainik/relude/issues/430):+ Upgrade dependencies:+ - `ghc-prim-0.9`+ - `mtl-2.3`+ - `hedgehog-1.2`+ - `doctest-0.21`+- Drop support of GHC-8.2.++## 1.1.0.0 — Jun 9, 2022++- [#388](https://github.com/kowainik/relude/issues/388):+ Support GHC-9.2.+- [#363](https://github.com/kowainik/relude/issues/363):+ Remove the `Option` type, reexported from `Data.Semigroup`+ (which was removed in `base-4.16`, GHC 9.2)++ **Migration guide:** Use `Maybe` instead of `Option`.++- [#372](https://github.com/kowainik/relude/issues/372):+ Warn on usages of `readFileText`, `readFileLText`, `readFile` and `readFile'`.++ > _NOTE:_ This is a **breaking change** if you build with `-Werror`+ > and use the above functions. Use `readFileBS` / `readFileLBS`+ > instead to convert to `Text` / `LText` / `String` using+ > `decodeUtf8` and similar functions.++- [#394](https://github.com/kowainik/relude/issues/394):+ Support `hashable-1.4`.+- [#408](https://github.com/kowainik/relude/issues/408):+ Switch benchmarks from `criterion` to `tasty-bench`.+- [#404](https://github.com/kowainik/relude/issues/404):+ Fix condidion for `ordNubOn`, `intNub`, `intNubOn` export for `Relude.Nub` module.+ Use min version of `containers-0.6.0` instead of min version of GHC `8.4`.+- Minor documentation improvements and fixes.++## 1.0.0.1 — Mar 15, 2021++- Minor documentation changes.++## 1.0.0.0 — Mar 12, 2021++- [#353](https://github.com/kowainik/relude/issues/353):+ Reexport most common modules from the following libraries:++ - `containers`+ - `unordered-containers`+ - `text`+ - `bytestring`++ Now, when using `relude`, you don't need to add these libraries to+ your `.cabal` file to enjoy their main API. Try removing them from+ your `.cabal` file after upgrading to this version of `relude` to+ see if you still need them.++ To utilise this feature, update the `mixin` part of your package+ configuration (if you're using the mixins approach) to the following:++ ```cabal+ mixins: base hiding (Prelude)+ , relude (Relude as Prelude)+ , relude+ ```++- [#345](https://github.com/kowainik/relude/issues/345):+ Support GHC-9.0.+- Upgrade minor GHC versions to GHC-8.10.4 and GHC-8.8.4.+- [#268](https://github.com/kowainik/relude/issues/268):+ Drop support of GHC-8.0.2.+- [#270](https://github.com/kowainik/relude/issues/270):+ Standardise `universe`, `universeNonEmpty` and `inverseMap` functions that+ previously were introduced in the `Relude.Extra.Enum` module. `Relude.Enum`+ module created that is exported in the main `Relude` module by default.++ **Migration guide:** If you were using any of these functions you can now+ remove `Relude.Extra.Enum` from your imports and explicit `mixins` section+ as they are available for you with the `Relude` module.++- Remove the `Eq` constraint on `universeNonEmpty`+- [#269](https://github.com/kowainik/relude/issues/269):+ Remove the `Relude.Extra.Validation` module.++ **Migration guide:**+ 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 (..), ..)+ ```++- [#346](https://github.com/kowainik/relude/issues/346),+ [#347](https://github.com/kowainik/relude/issues/347):+ Reimplement `ordNub` through `nubOrd` from `containers`.+ Add `ordNubOn`, `intNub` and `intNubOn` functions.+- [#327](https://github.com/kowainik/relude/issues/327):+ Add `infinitely` as more strictly typed `forever`.+- [#311](https://github.com/kowainik/relude/issues/311):+ Add `maybeAt` function — the non-operator version of `!!?` with its+ arguments flipped.+- [#314](https://github.com/kowainik/relude/issues/314):+ Add lifted versions of functions to work with `Handle`:++ - `hFlush`+ - `hIsEOF`+ - `hSetBuffering`+ - `hGetBuffering`++- [#305](https://github.com/kowainik/relude/issues/305):+ Add lifted versions of functions to work with environment:++ - `getArgs`+ - `lookupEnv`++- Add lifted version of the `readFile'` function.+- Reexport the `BufferMode` type from `base`.+- [#309](https://github.com/kowainik/relude/issues/309):+ Reexport `span` from `Data.List`.+- [#319](https://github.com/kowainik/relude/issues/319):+ Implement `partitionWith`.+- [#307](https://github.com/kowainik/relude/issues/307):+ Add `foldr1` to `Foldable1`.+- [#316](https://github.com/kowainik/relude/issues/316):+ Add `average` and `average1` — efficient functions for finding+ average on foldable structures.+- [#306](https://github.com/kowainik/relude/issues/306):+ Add `maximumOn1` and `minimumOn1` to `Foldable1`.+- [#301](https://github.com/kowainik/relude/issues/301):+ Add `traceShowWith` to `Relude.Debug`.+- [#304](https://github.com/kowainik/relude/issues/304),+ [#317](https://github.com/kowainik/relude/issues/317):+ Various documentation improvements.+- Updates to `relude`-specific `.hlint` rules.++Thanks @googleson78, @sushi-shi, @rektrex, @aleator, @mjgpy3, @dalpd,+@Bodigrim for helping with this release!+ ## 0.7.0.0 — May 14, 2020 -* [#253](https://github.com/kowainik/relude/issues/253):+- [#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):+- 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):+- [#256](https://github.com/kowainik/relude/issues/256): Make `cycle` total function.-* [#233](https://github.com/kowainik/relude/issues/233):+- [#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):+- [#294](https://github.com/kowainik/relude/issues/294): Add `atomicModifyIORef_` and `atomicModifyIORef'_`.-* [#293](https://github.com/kowainik/relude/issues/293):+- [#293](https://github.com/kowainik/relude/issues/293): Add `memptyIfFalse` and `memptyIfTrue` functions.-* Reexport `NonEmpty` functions from `Relude.List.NonEmpty` instead of+- Reexport `NonEmpty` functions from `Relude.List.NonEmpty` instead of `Relude.List.Reexport`.-* [#239](https://github.com/kowainik/relude/issues/239):+- [#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):+- [#227](https://github.com/kowainik/relude/issues/227): Create `Relude.Extra` module-* [#228](https://github.com/kowainik/relude/issues/228):+- [#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.+- [#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):+- 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+ **Migration rules:** -* [#246](https://github.com/kowainik/relude/issues/246):+ - `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:__+ **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`:+ 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):+ ```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:__+ **Migration rules:** - + Replace `mapToFst` with `toFst`- + Replace `mapToSnd` with `toSnd`- + You can now use `fmapToFst` and `fmapToSnd` instead of+ - 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++- [#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+ **Migration rules:** Use one of the conversion function from the `Relude.String.Conversion` module to covert your old input value into `String`. @@ -96,92 +275,96 @@ readEither @Int (toString myText) ``` -* [#281](https://github.com/kowainik/relude/issues/281):+- [#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):+- [#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):+- [#171](https://github.com/kowainik/relude/issues/171): Add custom type errors to various functions and instances.- + `head`, `tail`, `last`, `init`- + `words`, `unwords`, `lines`, `unlines`- + `error`- + `ToText`, `ToLText`, `ToString` instances for bytestrings- + `Foldable1` instance for ordinary lists- + `Monad` instance for `Validation` + - `head`, `tail`, `last`, `init`+ - `words`, `unwords`, `lines`, `unlines`+ - `error`+ - `ToText`, `ToLText`, `ToString` instances for bytestrings+ - `Foldable1` instance for ordinary lists+ - `Monad` instance for `Validation`+ (by [@vrom911](https://github.com/vrom911), [@chshersh](https://github.com/chshersh))-* [#164](https://github.com/kowainik/relude/issues/164):++- [#164](https://github.com/kowainik/relude/issues/164): Reexport `ShortByteString`, `toShort`/`fromShort` functions. (by [@vrom911](https://github.com/vrom911))-* [#182](https://github.com/kowainik/relude/issues/182):+- [#182](https://github.com/kowainik/relude/issues/182): Support GHC-8.8.1. (by [@chshersh](https://github.com/chshersh))-* [#168](https://github.com/kowainik/relude/pull/168),+- [#168](https://github.com/kowainik/relude/pull/168), [#197](https://github.com/kowainik/relude/pull/197): Improve documentation significantly (more and better examples, better wording). (by [@chshersh](https://github.com/chshersh), [@vrom911](https://github.com/vrom911), [@Cmdv](https://github.com/Cmdv))-* [#177](https://github.com/kowainik/relude/issues/177):+- [#177](https://github.com/kowainik/relude/issues/177): Improve usage of performance pragmas. (by [@chshersh](https://github.com/chshersh))-* [#167](https://github.com/kowainik/relude/issues/167):+- [#167](https://github.com/kowainik/relude/issues/167): Rename functions (and deprecate old versions):- + `prec` to `prev`- + `dupe` to `dup` + - `prec` to `prev`+ - `dupe` to `dup`+ (by [@Cmdv](https://github.com/Cmdv), [@chshersh](https://github.com/chshersh))-* [#192](https://github.com/kowainik/relude/issues/192):++- [#192](https://github.com/kowainik/relude/issues/192): Reexport `foldMap'` from `Data.Foldable`. (by [@tfausak](https://github.com/tfausak))-* [#201](https://github.com/kowainik/relude/issues/201):+- [#201](https://github.com/kowainik/relude/issues/201): Implement `!!?` as a safe equivalent of `!!` that returns a `Maybe`. (by [@kutyel](https://github.com/kutyel))-* [#203](https://github.com/kowainik/relude/issues/203):+- [#203](https://github.com/kowainik/relude/issues/203): Implement the `guarded` combinator. (by [@JonathanLorimer](https://github.com/JonathanLorimer))-* [#214](https://github.com/kowainik/relude/issues/214):+- [#214](https://github.com/kowainik/relude/issues/214): Add `mapMaybeM` function. (by [@vrom911](https://github.com/vrom911))-* [#174](https://github.com/kowainik/relude/issues/174):+- [#174](https://github.com/kowainik/relude/issues/174): Implement `bimapBoth` in `Relude.Extra.Tuple` module, mark `mapBoth` as DEPRECATED. (by [@astynax](https://github.com/astynax))-* [#221](https://github.com/kowainik/relude/issues/221):+- [#221](https://github.com/kowainik/relude/issues/221): Improve documentation for the `Validation` module significantly. (by [@chshersh](https://github.com/chshersh))-* [#176](https://github.com/kowainik/relude/issues/176):+- [#176](https://github.com/kowainik/relude/issues/176): Implement property-based tests for `Validation` laws. (by [@astynax](https://github.com/astynax))-* [#172](https://github.com/kowainik/relude/issues/172):+- [#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/issues/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):+- [#170](https://github.com/kowainik/relude/issues/170): Implement `Elem` type family. (by [@kutyel](https://github.com/kutyel))-* [#165](https://github.com/kowainik/relude/pull/165):+- [#165](https://github.com/kowainik/relude/pull/165): Re-export `GHC.Float.atan2`. (by [@ethercrow](https://github.com/ethercrow))-* [#155](https://github.com/kowainik/relude/issue/155):+- [#155](https://github.com/kowainik/relude/issue/155): Implement `foldlSC` — short-circuting list fold — in `Relude.Extra.Foldable`. (by [@josephcsible](https://github.com/josephcsible))-* [#158](https://github.com/kowainik/relude/issue/158):+- [#158](https://github.com/kowainik/relude/issue/158): Support GHC-8.6.5. (by [@chshersh](https://github.com/chshersh))-* [#148](https://github.com/kowainik/relude/issues/148):+- [#148](https://github.com/kowainik/relude/issues/148): Migrate HLint rules to the latest Dhall spec. (by [@vrom911](https://github.com/vrom911))-* [#178](https://github.com/kowainik/relude/issues/178):+- [#178](https://github.com/kowainik/relude/issues/178): Made `die` be polymorphic in its return type. (by [@ilyakooo0](https://github.com/ilyakooo0))-* [#162](https://github.com/kowainik/relude/pull/162),+- [#162](https://github.com/kowainik/relude/pull/162), [#189](https://github.com/kowainik/relude/pull/189), [#190](https://github.com/kowainik/relude/pull/190), [#191](https://github.com/kowainik/relude/pull/191),@@ -189,83 +372,85 @@ [#194](https://github.com/kowainik/relude/pull/194), [#195](https://github.com/kowainik/relude/pull/195): Various refactorings and code improvements:- + __Breaking change:__ Reorder type parameters to `asumMap`- + Implement `andM`, `orM`, `allM`, and `anyM` in terms of `&&^` and `||^`- + Use `foldr` instead of explicit recursion and `toList`- + Use `mapToFst` instead of `zip` to improve list fusion in `inverseMap`- + Implement `foldMap1` for `NonEmpty` in terms of `foldr`- + Use `$>` instead of `*>` and `pure` where possible- + Implement `asumMap` and `foldMapA` by coercing `foldMap`- + Return Failure early in `<*` and `*>` too + - **Breaking change:** Reorder type parameters to `asumMap`+ - Implement `andM`, `orM`, `allM`, and `anyM` in terms of `&&^` and `||^`+ - Use `foldr` instead of explicit recursion and `toList`+ - Use `mapToFst` instead of `zip` to improve list fusion in `inverseMap`+ - Implement `foldMap1` for `NonEmpty` in terms of `foldr`+ - Use `$>` instead of `*>` and `pure` where possible+ - Implement `asumMap` and `foldMapA` by coercing `foldMap`+ - Return Failure early in `<*` and `*>` too+ (by [@josephcsible](https://github.com/josephcsible))-* [#187](https://github.com/kowainik/relude/issues/187):++- [#187](https://github.com/kowainik/relude/issues/187): Remove `tasty` and `tasty-hedgehog` dependencies and their redundant imports. (by [@dalpd](https://github.com/dalpd)) ## 0.5.0 — Mar 18, 2019 -* [#127](https://github.com/kowainik/relude/issues/127):+- [#127](https://github.com/kowainik/relude/issues/127): Implement `Relude.Extra.Lens` module.-* [#125](https://github.com/kowainik/relude/issues/125):+- [#125](https://github.com/kowainik/relude/issues/125): Moved many numerical functions and types in `Relude.Numeric`. Reexport `toIntegralSized` from `Data.Bits`. Add `integerToBounded` and `integerToNatural` in `Relude.Numeric`.-* [#121](https://github.com/kowainik/relude/issues/121):+- [#121](https://github.com/kowainik/relude/issues/121): Reexport `Ap` from `Data.Monoid`. Change definition of `foldMapA` to use `Ap`.-* [#129](https://github.com/kowainik/relude/issues/129):+- [#129](https://github.com/kowainik/relude/issues/129): Add `appliedTo` and `chainedTo` as named versions of operators `=<<` and `<**>`.-* [#138](https://github.com/kowainik/relude/issues/138):+- [#138](https://github.com/kowainik/relude/issues/138): Add `RealFloat` to `Relude.Numeric`.-* [#144](https://github.com/kowainik/relude/issues/144):+- [#144](https://github.com/kowainik/relude/issues/144): Add `traverseToSnd` and friends to `Relude.Extra.Tuple`.-* [#140](https://github.com/kowainik/relude/issues/140):+- [#140](https://github.com/kowainik/relude/issues/140): Improve text of custom compile-time error messages for `elem` functions.-* [#136](https://github.com/kowainik/relude/issues/136):+- [#136](https://github.com/kowainik/relude/issues/136): Cover `Relude.Extra.*` modules with custom HLint rules.-* [#146](https://github.com/kowainik/relude/issues/146):+- [#146](https://github.com/kowainik/relude/issues/146): Improve documentation for `Relude.File` file: be more explicit about system locale issues.-* Improve documentation for `One` typeclass and add tests.-* Support ghc-8.6.4 and ghc-8.4.4.+- Improve documentation for `One` typeclass and add tests.+- Support ghc-8.6.4 and ghc-8.4.4. Drop support for ghc-8.6.1 and ghc-8.4.3. ## 0.4.0 — Nov 6, 2018 -* [#70](https://github.com/kowainik/relude/issues/70):+- [#70](https://github.com/kowainik/relude/issues/70): Reexport `Contravariant` for GHC >= 8.6.1.-* [#103](https://github.com/kowainik/relude/pull/104):+- [#103](https://github.com/kowainik/relude/pull/104): Drop `utf8-string` dependency and improve performance of conversion functions.-* [#98](https://github.com/kowainik/relude/issues/98):+- [#98](https://github.com/kowainik/relude/issues/98): Reexport `Bifoldable` related stuff from `base`.-* [#99](https://github.com/kowainik/relude/issues/99):+- [#99](https://github.com/kowainik/relude/issues/99): Reexport `Bitraversable` related stuff from `base`.-* [#100](https://github.com/kowainik/relude/issues/100):+- [#100](https://github.com/kowainik/relude/issues/100): Add `Relude.Extra.Validation` with `Validation`data type.-* [#89](https://github.com/kowainik/relude/issues/89):+- [#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)+- [#92](https://github.com/kowainik/relude/issues/92) Add `Relude.Extra.Tuple` module, containing `dupe`, `mapToFst`, `mapToSnd`, and `mapBoth` functions.-* [#97](https://github.com/kowainik/relude/issues/97):+- [#97](https://github.com/kowainik/relude/issues/97): Add `(&&^)` and `(||^)` operators.-* [#81](https://github.com/kowainik/relude/issues/81):+- [#81](https://github.com/kowainik/relude/issues/81): Add `asumMap` to `Foldable` functions.-* [#80](https://github.com/kowainik/relude/issues/80):+- [#80](https://github.com/kowainik/relude/issues/80): Add hlint rules for `whenLeft`, `whenLeftM`, `whenRight` and `whenRightM`.-* [#79](https://github.com/kowainik/relude/issues/79):+- [#79](https://github.com/kowainik/relude/issues/79): Add HLint rules for `One` typeclass.-* Remove `openFile` and `hClose`.-* [#83](https://github.com/kowainik/relude/pull/83):+- Remove `openFile` and `hClose`.+- [#83](https://github.com/kowainik/relude/pull/83): Make documentation for `nub` functions prettier.-* [#109](https://github.com/kowainik/relude/issues/109):+- [#109](https://github.com/kowainik/relude/issues/109): Use Dhall v3.0.0 for hlint file generation. ## 0.3.0 -* [#41](https://github.com/kowainik/relude/issues/41):+- [#41](https://github.com/kowainik/relude/issues/41): Add `Foldable1`.-* [#63](https://github.com/kowainik/relude/issues/63):+- [#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`.@@ -273,41 +458,42 @@ **Important:** this is a breaking change. If you used polymorphic `putStrLn` you need to remove type application or switch to one of the monomorphic functions. Also, you can't abstract over `Print` typeclass anymore.-* [#66](https://github.com/kowainik/relude/issues/66):++- [#66](https://github.com/kowainik/relude/issues/66): Export `(>>>)` and `(<<<)` from `Control.Category`.-* [#59](https://github.com/kowainik/relude/issues/59):+- [#59](https://github.com/kowainik/relude/issues/59): Introduce `flap` function and its operator version `??`.-* [#64](https://github.com/kowainik/relude/issues/64):+- [#64](https://github.com/kowainik/relude/issues/64): Improve performance of functions from `Foldable1`. Add `foldl1'` function.-* Reexport `uncons` from `base`.-* Rewrite `die` implementation to use `die` from `base`.-* [#19](https://github.com/kowainik/relude/issues/19):+- Reexport `uncons` from `base`.+- Rewrite `die` implementation to use `die` from `base`.+- [#19](https://github.com/kowainik/relude/issues/19): Rewrite `.hlint.yaml` to Dhall.-* Move `stdin`- and `stdout`-related functions to new module `Relude.Lifted.Terminal`.-* [#67](https://github.com/kowainik/relude/issues/67):+- Move `stdin`- and `stdout`-related functions to new module `Relude.Lifted.Terminal`.+- [#67](https://github.com/kowainik/relude/issues/67): Add HLint rules for `put*` functions.-* [#22](https://github.com/kowainik/relude/issues/22):+- [#22](https://github.com/kowainik/relude/issues/22): `readFile`, `writeFile` and `appendFile` now work with `String`. Add lifted version of `hClose`. Add `readFile`, `writeFile` and `appendFile` alternatives for `Text` and `ByteString`.-* [#61](https://github.com/kowainik/relude/issues/61):+- [#61](https://github.com/kowainik/relude/issues/61): Add `under2` and `underF2` functions to `Relude.Extra.Newtype`.-* [#60](https://github.com/kowainik/relude/issues/60):+- [#60](https://github.com/kowainik/relude/issues/60): Add `hoistMaybe` and `hoistEither` functions. ## 0.2.0 -* [#43](https://github.com/kowainik/relude/issues/43):+- [#43](https://github.com/kowainik/relude/issues/43): Implement `Relude.Extra.Newtype` module.-* [#46](https://github.com/kowainik/relude/issues/46):+- [#46](https://github.com/kowainik/relude/issues/46): Add a function that returns its own name.-* [#48](https://github.com/kowainik/relude/issues/48):+- [#48](https://github.com/kowainik/relude/issues/48): Export `<&>` from `base`. Also reexport `fromLeft` and `fromRight` from `base` where possible.-* [#49](https://github.com/kowainik/relude/issues/49):+- [#49](https://github.com/kowainik/relude/issues/49): Speed up and refactor property tests.-* [#54](https://github.com/kowainik/relude/issues/54):+- [#54](https://github.com/kowainik/relude/issues/54): Improve documentation. Add more examples to documentation and more tests. Reexport `withReader` and `withReaderT`.@@ -316,48 +502,48 @@ ## 0.1.1 -* [#44](https://github.com/kowainik/relude/issues/44):+- [#44](https://github.com/kowainik/relude/issues/44): Implement parser deriviation from pretty-printers. ## 0.1.0 -* [#7](https://github.com/kowainik/relude/issues/7):+- [#7](https://github.com/kowainik/relude/issues/7): Remove `Container.Class.Container`. Export `Foldable`.-* [#2](https://github.com/kowainik/relude/issues/2):+- [#2](https://github.com/kowainik/relude/issues/2): Remove `microlens` from dependencies.-* [#10](https://github.com/kowainik/relude/issues/10):+- [#10](https://github.com/kowainik/relude/issues/10): Remove `VarArg` module.-* [#9](https://github.com/kowainik/relude/issues/9):+- [#9](https://github.com/kowainik/relude/issues/9): Remove `safe-exceptions` from dependencies. Reexport `Exception` and `SomeException` from `Control.Exception` instead.-* [#11](https://github.com/kowainik/relude/issues/11):+- [#11](https://github.com/kowainik/relude/issues/11): Remove `TypeOps` module and `type-operators` dependency.-* [#13](https://github.com/kowainik/relude/issues/13):+- [#13](https://github.com/kowainik/relude/issues/13): Remove `list`, `getContents`, `interact`, `getArgs`, `note` functions. Remove `Lifted.ST` module. Rename `Lifted.Env` to `Lifted.Exit`.-* [#16](https://github.com/kowainik/relude/issues/16):+- [#16](https://github.com/kowainik/relude/issues/16): Rename `whenLeft`, `whenRight`, `whenLeftM`, `whenRightM` to `whenLeft_` and `whenRight_`, `whenLeftM_` and `whenRightM_`. Add `whenLeft`, `whenRight`, `whenLeftM`, `whenRightM` which return the value.-* [#18](https://github.com/kowainik/relude/issues/18):+- [#18](https://github.com/kowainik/relude/issues/18): Add `LazyStrict` type class for conversions.-* `map` is not `fmap` anymore. Reexport `map` from `Data.List`-* [#12](https://github.com/kowainik/relude/issues/12):+- `map` is not `fmap` anymore. Reexport `map` from `Data.List`+- [#12](https://github.com/kowainik/relude/issues/12): Remove `liquid-haskell` support.-* [#20](https://github.com/kowainik/relude/issues/20):+- [#20](https://github.com/kowainik/relude/issues/20): Add `viaNonEmpty` function.-* [#21](https://github.com/kowainik/relude/issues/21):+- [#21](https://github.com/kowainik/relude/issues/21): Add `MonadFail` instance for `Either`.-* [#17](https://github.com/kowainik/relude/issues/17):+- [#17](https://github.com/kowainik/relude/issues/17): Add `foldMapA` and `foldMapM` functions.-* [#4](https://github.com/kowainik/relude/issues/4):+- [#4](https://github.com/kowainik/relude/issues/4): Rename package to `Relude`.-* [#14](https://github.com/kowainik/relude/issues/14):+- [#14](https://github.com/kowainik/relude/issues/14): Add `Relude.Extra.*` modules which are not exported by default but have useful functions.-* [#8](https://github.com/kowainik/relude/issues/8):+- [#8](https://github.com/kowainik/relude/issues/8): Introduce `StaticMap` and `DynamicMap` type classes as universal interface for Map-like structures.
README.md view
@@ -3,8 +3,6 @@  [](https://github.com/kowainik/relude/actions)-[](http://travis-ci.org/kowainik/relude)-[](https://ci.appveyor.com/project/kowainik/relude) [](https://hackage.haskell.org/package/relude) [](http://stackage.org/lts/package/relude) [](http://stackage.org/nightly/package/relude)@@ -13,7 +11,7 @@ **`relude`** is a safe, performant, user-friendly and lightweight Haskell standard library. -The default `Prelude` is not perfect and doesn't always satisfies one's needs.+The default `Prelude` is not perfect and doesn't always satisfy 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.@@ -34,55 +32,61 @@ `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` |+| **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+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+ _Example:_ Here the function's name type and actions are aligned with each other - ```haskell- whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f ()- ```- While in here, the type could represent an unreachable state:+ ```haskell+ whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f ()+ ``` - ```haskell- whenNotNull :: Applicative f => [a] -> ([a] -> f ()) -> f ()- ```+ While in here, the type could represent an unreachable state: + ```haskell+ whenNotNull :: Applicative f => [a] -> ([a] -> f ()) -> f ()+ ```+ 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.+ (e.g. `Map`, `HashMap`, `Set`) more accessible. -5. **Minimalism** (low number of dependencies). We don not force users of+5. **Minimalism** (low number of dependencies). We do 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)+ The [Dependency graph](https://raw.githubusercontent.com/kowainik/relude/main/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` + - No need to add `containers`, `unordered-containers`, `text` and+ `bytestring` to dependencies in your `.cabal` file to use the+ main API of these libraries+ - No need to import types like `NonEmpty`, `Text`, `Set`, `Reader[T]`, `MVar`, `STM`+ - Functions like `liftIO`, `fromMaybe`, `sortWith` are available 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++ - Tutorial+ - Migration guide from `Prelude`+ - 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`](https://github.com/kowainik/relude/blob/master/.hlint.yaml)+ - 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`](https://github.com/kowainik/relude/blob/main/.hlint.yaml) 8. **User-friendliness.** Anyone should be able to quickly migrate to `relude`. Only some basic familiarity with the common libraries like `text` and `containers`@@ -113,23 +117,28 @@ blog post by [Type Classes](https://typeclasses.com/) that highlights `relude`. -* [No implicit Prelude](https://typeclasses.com/ghc/no-implicit-prelude)+- [No implicit Prelude](https://typeclasses.com/ghc/no-implicit-prelude) +For guiding development principles behind `relude` and comparison with+`base`, check out the following talk:++- [](https://www.youtube.com/watch?v=qwAmiJ5M_zM)+ ## 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)- * [Mixins](#mixins)- * [base-noprelude](#base-noprelude)- * [NoImplicitPrelude](#NoImplicitPrelude)+ - [Mixins](#mixins)+ - [NoImplicitPrelude](#noimplicitprelude)+ - [base-noprelude (not recommended)](#base-noprelude) 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)+ - [Relude vs Protolude](#relude-vs-protolude) 8. [For developers](#for-developers) This is neither a tutorial on _Haskell Standard Library_ nor a tutorial on each@@ -150,13 +159,13 @@ Replacing default `Prelude` from `base` has the following _disadvantages_: -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.+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 the boot libraries (almost) which results in small+ - `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. @@ -202,10 +211,18 @@ ```haskell mixins: base hiding (Prelude) , relude (Relude as Prelude)+ , relude ``` > **NOTE:** this requires Cabal version to be at least `2.2` +The above syntax does the following:++1. Makes all modules of `base` available except `Prelude`.+2. Renames the `Relude` module in `relude` to `Prelude`.+3. Additionally allows importing all other modules from `relude`+ (extra modules and reexports from other libraries).+ See the following complete example of how your `.cabal` file may look like after the set up: @@ -216,11 +233,12 @@ library exposed-modules: Example- build-depends: base >= 4.10 && < 4.13- , relude ^>= 0.6.0.0+ build-depends: base >= 4.14 && < 4.17+ , relude ^>= 1.1.0.0 mixins: base hiding (Prelude) , relude (Relude as Prelude)+ , relude default-language: Haskell2010 ```@@ -229,19 +247,21 @@ > 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:+If you want to restrict allowed modules in `relude` to a specific list+(e.g. use only `Relude.Extra.Enum` or `Relude.Unsafe` or `Data.Text`+from `text`), you can alternatively list them explicitly under the+first `mixins` entry field as well, like this: ```cabal mixins: base hiding (Prelude) , relude (Relude as Prelude , Relude.Extra.Enum- , ...+ , Relude.Unsafe+ , Data.Text ) ``` -If you want to bring all `Extra.*` modules into scope, you can add+If you want to bring only 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@@ -254,10 +274,47 @@ ) ``` +> **NOTE:** due to the existing [stack issue](https://github.com/commercialhaskell/stack/issues/5077),+> `mixins` technique doesn't work with the `stack repl` at the moment. Please,+> consider this before using this method of turning `relude` on in the project.+>+> If having `stack repl` crucial for your workflow, see the following options of+> how to use Relude in your project.++### 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 #-}+```++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+```++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+```+ ### base-noprelude [[Back to the Table of Contents] ↑](#structure-of-this-tutorial) +:warning: _This strategy is not reccommended. The package `base-noprelude` is currently not being maintained and its use is likely to cause issues with newer versions of ghc and libraries._+ 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@@ -268,6 +325,7 @@ 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@@ -275,6 +333,7 @@ import Relude ```+ 4. Add this module to `exposed-modules` in your `.cabal` file: ```cabal exposed-modules: Prelude@@ -288,59 +347,31 @@ 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 #-}-```--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-```--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 [[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]`.+- 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 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`.+ - `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 due to performance reasons.- + `error` takes `Text`.- + `undefined` triggers a compiler warning, because you probably don't want to+ - `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`.-* Not reexported- + `read`- + `lookup` for lists- + `log`-* Completely new functions are brought into scope- + See the [What's new?](#whats-new) section for a detailed overview.-* New reexports- + See the [Reexports](#reexports) section for a detailed overview.+- Not reexported+ - `read`+ - `lookup` for lists+ - `log`+- Completely new functions are brought into scope+ - See the [What's new?](#whats-new) section for a detailed overview.+- New reexports+ - See the [Reexports](#reexports) section for a detailed overview. ## Reexports @@ -348,21 +379,21 @@ `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)-* [`text`](http://hackage.haskell.org/package/text)-* [`transformers`](http://hackage.haskell.org/package/transformers)-* [`unordered-containers`](http://hackage.haskell.org/package/unordered-containers)+- [`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)+- [`text`](http://hackage.haskell.org/package/text)+- [`transformers`](http://hackage.haskell.org/package/transformers)+- [`unordered-containers`](http://hackage.haskell.org/package/unordered-containers) 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)+[`.hlint.yaml`](https://github.com/kowainik/relude/blob/main/.hlint.yaml) configuration for this task. With this config, `HLint` will produce warnings and hints on how to have more benefits from `relude`. @@ -370,14 +401,14 @@ 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).+- `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 similar to `read` but unlike it, they are total and return either `Maybe` or `Either` with a parse error.@@ -385,9 +416,9 @@ `(&)` is the reverse application. The following three expressions are semantically equivalent: -* `g (f x)`-* `g $ f $ x`-* `x & f & g`+- `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`,@@ -399,10 +430,10 @@ [`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 the first and+- `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.+- `bimap` takes two functions and applies them to the first and second parts respectively. `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`@@ -422,9 +453,9 @@ The following types from these two packages are exported: -* Maps: strict versions of `Map`, `HashMap`, `IntMap`.-* Sets: `Set`, `HashSet`, `IntSet`.-* Sequences: `Seq`.+- Maps: strict versions of `Map`, `HashMap`, `IntMap`.+- Sets: `Set`, `HashSet`, `IntSet`.+- Sequences: `Seq`. ### text & bytestring @@ -448,8 +479,8 @@ The following parts of these two libraries are exported: -* Transformers: `State[T]`, `Reader[T]`, `ExceptT`, `MaybeT`.-* Classes: `MonadReader`, `MonadState`.+- Transformers: `State[T]`, `Reader[T]`, `ExceptT`, `MaybeT`.+- Classes: `MonadReader`, `MonadState`. ### Deepseq @@ -468,7 +499,8 @@ ### Available by default -* Safe analogue for the list functions:+- 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@@ -487,17 +519,18 @@ Nothing ``` -* `uncons` splits a list at the first element.-* `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+- `uncons` splits a list at the first element.+- `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`,+ and `intNub` for fast `Int`s nub.+- `whenM`, `unlessM`, `ifM`, `guardM` — monadic guard combinators, that work with any `Monad`, e.g. `whenM (doesFileExist "foo")`.-* General fold functions:+- 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][_]` functions that+- `when(Just|Nothing|Left|Right|NotEmpty)[M][_]` functions that let you conditionally execute something. **Before:**@@ -515,23 +548,23 @@ f x ``` -* `for_` and `forM_` for loops.+- `for_` and `forM_` for loops. ```haskell for_ files $ \file -> do ... ``` -* `andM`, `allM`, `anyM`, `orM` are monadic versions of the corresponding+- `andM`, `allM`, `anyM`, `orM` are monadic versions of the corresponding functions from `base`.-* Conversions between `Either` and `Maybe`, e.g. `rightToMaybe` and `maybeToLeft`+- 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](http://hackage.haskell.org/package/relude/docs/Relude-Container-One.html)+- `using(Reader|State)[T]` functions as aliases for `flip run(Reader|State)[T]`.+- [`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+- `evaluateWHNF` and `evaluateNF` functions as clearer and lifted aliases for `evaluate` and `evaluate . force`.-* `MonadFail` instance for `Either`.+- `MonadFail` instance for `Either`. ### Extra bonuses @@ -541,13 +574,15 @@ These extra modules include the following functionality: -* Convenient functions to work with `(Bounded a, Enum a)` types:+- Convenient functions to work with `(Bounded a, Enum a)` types:+ 1. `universe :: (Bounded a, Enum a) => [a]`: get all values of the type. ```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: @@ -556,7 +591,7 @@ readMyEnums = inverseMap myShow ``` -* Nice helpers to deal with `newtype`s in a more pleasant way:+- Nice helpers to deal with `newtype`s in a more pleasant way: ```haskell ghci> newtype Foo = Foo Bool deriving Show@@ -564,7 +599,7 @@ Foo False ``` -* Functions to operate with `CallStack`:+- Functions to operate with `CallStack`: ```haskell ghci> foo :: HasCallStack => String; foo = ownName@@ -572,11 +607,11 @@ "foo" ``` -* `Foldable1` typeclass that contains generalized interface for folding+- `Foldable1` typeclass that contains generalized interface for folding non-empty structures like `NonEmpty`.-* [`StaticMap` and `DynamicMap` type classes](src/Relude/Extra/Map.hs) as a+- [`StaticMap` and `DynamicMap` type classes](https://github.com/kowainik/relude/blob/main/src/Relude/Extra/Map.hs) as a general interface for `Map`-like data structures.-* And much more!+- And much more! Explore `Extra` modules: [`Relude.Extra`](http://hackage.haskell.org/package/relude/docs/Relude-Extra.html) @@ -588,7 +623,7 @@ 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.+instructions provided in the [_Get Started_](#get-started) section. ### Code changes @@ -600,50 +635,52 @@ 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`.+ - `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 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 is recommended to replace usages of such functions with the monomorhpic alternatives:- * `Maybe`- + `(?:) :: Maybe a -> a -> a`- + `fromMaybe :: a -> Maybe a -> a`- + `maybeToList :: Maybe a -> [a]`- + `maybeToMonoid :: Monoid m => Maybe m -> m`- + `maybe :: b -> (a -> b) -> Maybe a -> b`- + `whenJust :: Applicative f => Maybe a -> (a -> f ()) -> f ()`- + `whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m ()` - * `Either`- + `fromLeft :: a -> Either a b -> a`- + `fromRight :: b -> Either a b -> b`- + `either :: (a -> c) -> (b -> c) -> Either a b -> c`- + `whenRight_ :: Applicative f => Either l r -> (r -> f ()) -> f ()`- + `whenRightM_ :: Monad m => m (Either l r) -> (r -> m ()) -> m ()`+ - `Maybe` + - `(?:) :: Maybe a -> a -> a`+ - `fromMaybe :: a -> Maybe a -> a`+ - `maybeToList :: Maybe a -> [a]`+ - `maybeToMonoid :: Monoid m => Maybe m -> m`+ - `maybe :: b -> (a -> b) -> Maybe a -> b`+ - `whenJust :: Applicative f => Maybe a -> (a -> f ()) -> f ()`+ - `whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m ()`++ - `Either`+ - `fromLeft :: a -> Either a b -> a`+ - `fromRight :: b -> Either a b -> b`+ - `either :: (a -> c) -> (b -> c) -> Either a b -> c`+ - `whenRight_ :: Applicative f => Either l r -> (r -> f ()) -> f ()`+ - `whenRightM_ :: Monad m => m (Either l r) -> (r -> m ()) -> m ()`+ 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 in the following way:+ - 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. - ```haskell- import qualified Text.Show+6. Since `show` doesn't come from `Show` anymore, you need to import the+ `Text.Show` module if you want to implement `Show` instance manually. This can be done in the following way: - data MyType = ...+```haskell+import qualified Text.Show - instance Show MyType where- show :: MyType -> String- show = ...- ```+data MyType = ... -7. Run `hlint` using `.hlint.yaml` file from `relude` package to cleanup code and imports.+instance Show MyType where+ show :: MyType -> String+ show = ...+``` +7. Run `hlint` using `.hlint.yaml` file from `relude` package to cleanup code and imports. ### Running HLint on CI @@ -660,14 +697,14 @@ two commands on your CI: ```yaml-curl https://raw.githubusercontent.com/kowainik/relude/v0.6.0.0/.hlint.yaml -o .hlint-relude.yaml+curl https://raw.githubusercontent.com/kowainik/relude/v1.1.0.0/.hlint.yaml -o .hlint-relude.yaml 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 described in the following blog post about Travis CI settings: -* [Kodimensional: Dead simple Haskell Travis settings for cabal and stack](https://kodimensional.dev/posts/2019-02-25-haskell-travis#customization-hlint)+- [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 @@ -697,20 +734,20 @@ _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`+ supports from GHC 8.4. 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 scary in some places as a consequence and it is more difficult to add, remove or change things there. 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- * 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.-6. `relude` has less dependencies and is slightly lighter because of that but still+ - [High-level overview of internal module structure](http://hackage.haskell.org/package/relude/docs/Relude.html)+ - 100% Haddock coverage+ - 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.+6. `relude` has fewer 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. That means that we do not@@ -728,21 +765,19 @@ Note, that we are using custom `hlint` setting which are `Relude` specific. To keep it up to date don't forget to reflect your changes in this file. We are-using `Dhall` to maintain the configurations. To use it follow the steps below.+using `Dhall` to maintain the configurations (lang version 22.0.0). To+use it follow the steps below. First time: ```shell-$ cabal v2-install dhall-json+$ cabal v2-install dhall-yaml-1.2.10 ``` -Dhall 16.0.0 is required, so make sure that the previous command installed-`dhall-json` >= 1.6.4.- To generate `hlint` file: ```shell-$ dhall-to-yaml --omitNull <<< './hlint/hlint.dhall' > .hlint.yaml+$ dhall-to-yaml-ng <<< './hlint/hlint.dhall' > .hlint.yaml ``` Check that you have generated valid `.hlint.yaml` file without parse errors:@@ -753,4 +788,30 @@ See our blog post where we describe the details of the implementation for this solution: -* [Dhall To HLint](https://kowainik.github.io/posts/2018-09-09-dhall-to-hlint)+- [Dhall To HLint](https://kowainik.github.io/posts/2018-09-09-dhall-to-hlint)++### Producing dependency graph++Install `cabal-plan` first:++```shell+$ cabal v2-install cabal-plan+$ cabal-plan --version+cabal-plan 0.6.2.0+```++Then draw the graph only for the library dependencies:++```shell+cabal-plan dot --root lib:relude | dot -Tpng -o relude-dependency-graph.png+```++### Updating license headers++Install the `headroom` tool and run it from this repository:++```shell+cabal v2-install headroom-0.4.3.0+headroom run+rg "SPDX-License-Identifier : MPL-2.0" --files-with-matches src/ | xargs sed -i 's/SPDX-License-Identifier : MPL-2.0/SPDX-License-Identifier : MIT/g'+```
benchmark/Main.hs view
@@ -1,10 +1,11 @@+{-# LANGUAGE CPP #-}+ module Main (main) where import Relude hiding (show) import Data.List (nub)-import Gauge (Benchmark, bench, bgroup, nf)-import Gauge.Main (defaultMain)+import Test.Tasty.Bench (Benchmark, bench, bgroup, defaultMain, nf) import Prelude (show) import qualified Data.HashSet as HashSet (insert)@@ -17,6 +18,12 @@ , bgroupList listOfBig "big" , bgroupList (nStrings 'z') "small str" , bgroupList (nStrings 'c') "big str"++#if __GLASGOW_HASKELL__ > 804+ , bgroupIntList listOfSmall "small ints"+ , bgroupIntList listOfBig "big ints"+#endif+ , bgroupFold ] @@ -63,6 +70,33 @@ safeSort :: [a] -> [a] safeSort = map NonEmpty.head . NonEmpty.group . sort++#if __GLASGOW_HASKELL__ > 804+bgroupIntList+ :: (Int -> [Int])+ -> String+ -> Benchmark+bgroupIntList f name = bgroup name $ map ($ f)+ [ bgroupNub 100+ , bgroupNub 500+ , bgroupNub 1000+ , bgroupNub 5000+ , bgroupNub 500000+ , bgroupNub 1000000+ ]+ where+ bgroupNub :: Int -> (Int -> [Int]) -> Benchmark+ bgroupNub n listOf = bgroup (show n) nubBenchs+ where+ listN :: [Int]+ listN = listOf n++ nubBenchs :: [Benchmark]+ nubBenchs =+ [ bench "ordNub" $ nf ordNub listN+ , bench "intNub" $ nf intNub listN+ ]+#endif listOfSmall :: Int -> [Int] listOfSmall n = let part = n `div` 100 in concat $ replicate part [1..100]
relude.cabal view
@@ -1,24 +1,24 @@-cabal-version: 2.4+cabal-version: 3.0 name: relude-version: 0.7.0.0+version: 1.2.2.2 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 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.- .+ * __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__ | +=================================+============================================+@@ -30,51 +30,49 @@ +---------------------------------+--------------------------------------------+ | @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 () @- .++ /Example:/ @ whenNotNull :: Applicative f => [a] -> (NonEmpty a -> f ()) -> f () @+ * __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.- .- * __Minimalism__ (low number of dependencies). We don not force users of+ (e.g. @Map@, @HashMap@, @Set@) more accessible.++ * __Minimalism__ (low number of dependencies). We do 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)+ The [Dependency graph](https://raw.githubusercontent.com/kowainik/relude/main/relude-dependency-graph.png) of @relude@ can give you a clearer picture.- .+ * __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:- .- 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@- .++ 1. No need to add @containers@, @unordered-containers@, @text@+ and @bytestring@ to dependencies in your @.cabal@ file to+ use the main API of these libraries+ 2. No need to import types like @NonEmpty@, @Text@, @Set@, @Reader[T]@, @MVar@, @STM@+ 3. Functions like @liftIO@, @fromMaybe@, @sortWith@ are available by default as well+ 4. @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).- . 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)@- .+ 5. @relude@-specific [HLint](http://hackage.haskell.org/package/hlint) rules: @[.hlint.yaml](https://github.com/kowainik/relude/blob/main/.hlint.yaml)@+ * __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.__ 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@@ -87,18 +85,22 @@ 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-2020 Kowainik+copyright: 2016 Stephen Diehl, 2016-2018 Serokell, 2018-2023 Kowainik category: Prelude stability: stable build-type: Simple extra-doc-files: CHANGELOG.md README.md-tested-with: GHC == 8.0.2- GHC == 8.2.2- GHC == 8.4.4+tested-with: GHC == 8.4.4 GHC == 8.6.5- GHC == 8.8.3- GHC == 8.10.1+ GHC == 8.8.4+ GHC == 8.10.7+ GHC == 9.0.2+ GHC == 9.2.8+ GHC == 9.4.7+ GHC == 9.6.6+ GHC == 9.8.2+ GHC == 9.10.1 source-repository head@@ -106,18 +108,14 @@ location: git@github.com:kowainik/relude.git common common-options- build-depends: base >= 4.9 && < 4.15- ghc-options: -Wall -Wcompat -Widentities -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+ -Wredundant-constraints+ -fhide-source-paths if impl(ghc >= 8.4) ghc-options: -Wmissing-export-lists -Wpartial-fields@@ -125,6 +123,18 @@ ghc-options: -Wmissing-deriving-strategies if impl(ghc >= 8.10) ghc-options: -Wunused-packages+ if impl(ghc >= 9.0)+ ghc-options: -Winvalid-haddock+ if impl(ghc >= 9.2)+ ghc-options: -Wredundant-bang-patterns+ -Woperator-whitespace+ if impl(ghc >= 9.4 && < 9.10)+ ghc-options: -Wforall-identifier+ if impl(ghc >= 9.4)+ ghc-options: -Wredundant-strictness-flags+ if impl(ghc >= 9.8)+ ghc-options: -Wterm-variable-capture+ -Winconsistent-flags default-language: Haskell2010@@ -149,6 +159,7 @@ Relude.Container.Reexport Relude.Debug Relude.DeepSeq+ Relude.Enum Relude.Exception Relude.File Relude.Foldable@@ -164,6 +175,8 @@ Relude.Lifted.File Relude.Lifted.IORef Relude.Lifted.Terminal+ Relude.Lifted.Handle+ Relude.Lifted.Env Relude.List Relude.List.NonEmpty Relude.List.Reexport@@ -193,19 +206,45 @@ Relude.Extra.Newtype Relude.Extra.Tuple Relude.Extra.Type- Relude.Extra.Validation Relude.Unsafe + reexported-modules:+ -- containers+ , Data.IntMap.Lazy+ , Data.IntMap.Strict+ , Data.IntSet+ , Data.Map.Lazy+ , Data.Map.Strict+ , Data.Set+ , Data.Sequence+ , Data.Tree+ -- unordered-containers+ , Data.HashMap.Lazy+ , Data.HashMap.Strict+ , Data.HashSet+ -- text+ , Data.Text+ , Data.Text.IO+ , Data.Text.Lazy+ , Data.Text.Lazy.IO+ , Data.Text.Read+ -- bytestring+ , Data.ByteString+ , Data.ByteString.Builder+ , Data.ByteString.Lazy+ , Data.ByteString.Short - build-depends: bytestring ^>= 0.10- , containers >= 0.5.7 && < 0.7- , deepseq ^>= 1.4- , ghc-prim >= 0.4.0.0 && < 0.7- , hashable >= 1.2 && < 1.4- , mtl ^>= 2.2++ build-depends: base >= 4.11 && < 4.22+ , bytestring >= 0.10 && < 0.13+ , containers >= 0.5.10 && < 0.9+ , deepseq >= 1.4 && < 1.6+ , ghc-prim >= 0.5.0.0 && < 0.14+ , hashable >= 1.2 && < 1.6+ , mtl >= 2.2 && < 2.4 , stm >= 2.4 && < 2.6- , text ^>= 1.2- , transformers ^>= 0.5+ , text >= 1.2 && < 2.2+ , transformers >= 0.5 && < 0.7 , unordered-containers >= 0.2.7 && < 0.3 @@ -218,12 +257,12 @@ other-modules: Test.Relude.Gen Test.Relude.Container.One Test.Relude.Property- Test.Relude.Extra.Validation.Property- build-depends: relude+ build-depends: base+ , relude , bytestring , containers , text- , hedgehog ^>= 1.0+ , hedgehog >= 1.0 && < 1.6 ghc-options: -threaded @@ -234,7 +273,7 @@ main-is: Doctest.hs build-depends: relude- , doctest+ , doctest >= 0.20 && < 0.25 , Glob ghc-options: -threaded@@ -245,10 +284,9 @@ hs-source-dirs: benchmark main-is: Main.hs - build-depends: relude- , gauge+ build-depends: base+ , relude+ , tasty-bench , unordered-containers - ghc-options: -threaded- -rtsopts- -with-rtsopts=-N+ ghc-options: -rtsopts
src/Relude.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable @relude@ is a safe, performant, user-friendly and lightweight Haskell standard library.@@ -34,6 +35,7 @@ ... mixins: base hiding (Prelude) , relude (Relude as Prelude)+ , relude @ === @base-noprelude@@@ -93,6 +95,8 @@ -- $debug , module Relude.DeepSeq -- $deepseq+ , module Relude.Enum+ -- $enum , module Relude.Exception -- $exception , module Relude.File@@ -130,6 +134,7 @@ import Relude.Container import Relude.Debug import Relude.DeepSeq+import Relude.Enum import Relude.Exception import Relude.File import Relude.Foldable@@ -174,6 +179,11 @@ to evaluate expressions to weak-head normal form or normal form. -} +{- $enum+__"Relude.Enum"__ reexports 'Enum' related typeclasses and functions. Also+introduced a few useful helpers to work with Enums.+-}+ {- $exception __"Relude.Exception"__ contains reexports from "Control.Exception", introduces 'bug' function as better 'error' and 'Exc' pattern synonym for convenient@@ -253,7 +263,7 @@ | __"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 |+| __"Relude.Extra.Foldable1"__ | t'Relude.Extra.Foldable1.Foldable1' typeclass | | | like 'Foldable' but for non-empty structures. | +------------------------------+-----------------------------------------------------------+ | __"Relude.Extra.Group"__ | Grouping functions, polymorphic on return @Map@ type. |@@ -269,13 +279,6 @@ | __"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,14 +1,14 @@-{-# LANGUAGE CPP #-} {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Applicative+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable This module contains reexports of 'Applicative' and related functional. Additionally, it provides convenient combinators to work with 'Applicative'.@@ -21,9 +21,6 @@ , Applicative (..) , Const (..) , ZipList (..)-#if __GLASGOW_HASKELL__ < 802- , liftA2-#endif , liftA3 , optional , (<**>)@@ -41,16 +38,26 @@ -- >>> import Relude -- >>> import Relude.Monad (Maybe) --- | Shorter alias for @pure ()@.------ >>> pass :: Maybe ()--- Just ()+{- | Shorter alias for @pure ()@.++>>> pass :: Maybe ()+Just ()++Useful shortcut when need an empty action:++@+printJust :: Maybe Int -> IO ()+printJust mInt = case mInt of+ Just i -> putStrLn $ "Number: " ++ show i+ Nothing -> pass+@+-} pass :: Applicative f => f () pass = pure () {-# INLINE pass #-} -{- | Named version of the '<**>' operator, which is '<*>' but flipped. For-chaining applicative operations in forward applications using+{- | Named version of the '<**>' operator, which is '<*>' but flipped. It is+helpful for chaining applicative operations in forward applications using 'Relude.Function.&'. >>> Just (+ 1) & appliedTo (Just 2)
src/Relude/Base.hs view
@@ -1,14 +1,16 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE ExplicitNamespaces #-}+{-# LANGUAGE Trustworthy #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Base+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Reexports from @Data.*@ and @GHC.*@ modules of <https://hackage.haskell.org/package/base base> package.@@ -29,22 +31,19 @@ , module Data.Coerce , module Data.Kind , module Data.Proxy+#if __GLASGOW_HASKELL__ >= 904+ , module Data.Type.Equality+#endif , module Data.Typeable , module Data.Void -- * 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-#else- , module GHC.TypeLits-#endif- , module GHC.OverloadedLabels , module GHC.ExecutionStack , module GHC.Stack@@ -54,29 +53,27 @@ import Data.Char (Char, chr) -- IO-import System.IO (FilePath, Handle, IO, IOMode (..), stderr, stdin, stdout, withFile)+import System.IO (FilePath, IO, IOMode (..)) -- Base typeclasses-import Data.Eq (Eq (..))+import Data.Eq (Eq, (/=), (==)) import Data.Ord (Down (..), Ord (..), Ordering (..), comparing) -- Types for type-level computation import Data.Coerce (Coercible, coerce) import Data.Kind (Constraint, Type) import Data.Proxy (Proxy (..))+#if __GLASGOW_HASKELL__ >= 904+import Data.Type.Equality (type (~))+#endif import Data.Typeable (Typeable) import Data.Void (Void, absurd, vacuous) import GHC.Base (asTypeOf, ord, seq, ($!))-import GHC.Enum (Bounded (..), Enum (..), boundedEnumFrom, boundedEnumFromThen) import GHC.Generics (Generic) import GHC.Show (Show) -#if MIN_VERSION_base(4,10,0) import GHC.TypeNats (CmpNat, KnownNat, Nat, SomeNat (..), natVal, someNatVal)-#else-import GHC.TypeLits (CmpNat, KnownNat, Nat, SomeNat (..), natVal, someNatVal)-#endif import GHC.ExecutionStack (getStackTrace, showStackTrace) import GHC.OverloadedLabels (IsLabel (..))
src/Relude/Bool.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Bool+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+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.
src/Relude/Bool/Guard.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Bool.Guard+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Monadic boolean combinators. -}@@ -38,6 +39,7 @@ -- >>> import Relude (Int, String, even, const) {- | Monadic version of 'when'.+Conditionally executes the provided action. >>> whenM (pure False) $ putTextLn "No text :(" >>> whenM (pure True) $ putTextLn "Yes text :)"@@ -53,7 +55,8 @@ whenM p m = p >>= flip when m {-# INLINE whenM #-} -{- | Monadic version of 'unless'.+{- | Monadic version of 'unless'. Reverse of 'whenM'.+Conditionally don't execute the provided action. >>> unlessM (pure False) $ putTextLn "No text :(" No text :(@@ -67,12 +70,23 @@ >>> ifM (pure True) (putTextLn "True text") (putTextLn "False text") True text+>>> ifM (pure False) (putTextLn "True text") (putTextLn "False text")+False 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.+{- | Monadic version of 'guard' that help to check that a condition ('Bool')+holds inside. Works with 'Monad's that are also 'Alternative'.++>>> guardM (Just True)+Just ()+>>> guardM (Just False)+Nothing+>>> guardM Nothing+Nothing+ Here some complex but real-life example: @@@ -90,7 +104,7 @@ {-# INLINE guardM #-} {- | Either lifts a value into an alternative context or gives a-minimal value depending on a predicate.+minimal value depending on a predicate. Works with 'Alternative's. >>> guarded even 3 :: [Int] []@@ -118,8 +132,12 @@ guarded p a = if p a then pure a else empty {-# INLINE guarded #-} -{- | Monadic version of 'Data.Bool.(&&)' operator.+{- | Monadic version of '(Data.Bool.&&)' operator. +It is lazy by the second argument (similar to '(Data.Bool.||)'), meaning that if+the first argument is 'False', the function will return 'False' without evaluating+the second argument.+ >>> Just False &&^ Just True Just False >>> Just True &&^ Just True@@ -137,7 +155,11 @@ (&&^) e1 e2 = ifM e1 e2 (pure False) {-# INLINE (&&^) #-} -{- | Monadic version of 'Data.Bool.(||)' operator.+{- | Monadic version of '(Data.Bool.||)' operator.++It is lazy by the second argument (similar to '(Data.Bool.||)'), meaning that if+the first argument is 'True', the function will return 'True' without evaluating+the second argument. >>> Just False ||^ Just True Just True
src/Relude/Bool/Reexport.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Bool.Reexport+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Reexports functions to work with 'Bool' type. -}
src/Relude/Container.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Container+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable This module exports all container-related stuff. -}
src/Relude/Container/One.hs view
@@ -4,20 +4,22 @@ {-# LANGUAGE TypeFamilies #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Container.One+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable '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 @(:[])@.+3. Give a clearer and less scary name for cases where you can use 'Relude.Applicative.pure'+ or @(:[])@. @since 0.1.0 -}@@ -52,6 +54,7 @@ -- >>> import Relude {- | Typeclass for data types that can be created from one element.+E.g. lists, non-empty containers, maps. >>> one True :: [Bool] [True]@@ -68,7 +71,7 @@ this container) -} class One x where- -- | Type of single element of the structure.+ -- | Type of a single element of the structure. type OneItem x -- | Create a list, map, 'T.Text', etc from a single element.@@ -77,13 +80,13 @@ -- Lists {- | Allows to create a singleton list. You might prefer function with name 'one'-instead of 'Relude.pure' or @(:[])@.+instead of 'Relude.Applicative.pure' or @(:[])@. >>> one 42 :: [Int] [42] @-law> 'Relude.length' ('one' @[a] x) ≡ 1+law> 'Relude.Foldable.Reexport.length' ('one' @[a] x) ≡ 1 @ -} instance One [a] where@@ -94,13 +97,13 @@ {-# INLINE one #-} {- | Allows to create singleton 'NE.NonEmpty' list. You might prefer function with-name 'one' instead of 'Relude.pure' or @(:|[])@.+name 'one' instead of 'Relude.Applicative.pure' or @(:|[])@. >>> one 42 :: NonEmpty Int 42 :| [] @-law> 'Relude.length' ('one' @('NE.NonEmpty' a) x) ≡ 1+law> 'Relude.Foldable.Reexport.length' ('one' @('NE.NonEmpty' a) x) ≡ 1 @ -} instance One (NE.NonEmpty a) where@@ -116,7 +119,7 @@ fromList [42] @-law> 'Relude.length' ('one' @('SEQ.Seq' a) x) ≡ 1+law> 'Relude.Foldable.Reexport.length' ('one' @('SEQ.Seq' a) x) ≡ 1 @ -} instance One (SEQ.Seq a) where@@ -216,7 +219,7 @@ fromList [(3,"foo")] @-law> 'Relude.length' ('one' @('Map' k v) (k, v)) ≡ 1+law> 'Relude.Foldable.Reexport.length' ('one' @('Map' k v) (k, v)) ≡ 1 @ -} instance One (Map k v) where@@ -232,7 +235,7 @@ fromList [(3,"foo")] @-law> 'Relude.length' ('one' @('HashMap' k v) (k, v)) ≡ 1+law> 'Relude.Foldable.Reexport.length' ('one' @('HashMap' k v) (k, v)) ≡ 1 @ -} instance Hashable k => One (HashMap k v) where@@ -248,7 +251,7 @@ fromList [(3,"foo")] @-law> 'Relude.length' ('one' @('IntMap' a) x) ≡ 1+law> 'Relude.Foldable.Reexport.length' ('one' @('IntMap' a) x) ≡ 1 @ -} instance One (IntMap v) where@@ -266,7 +269,7 @@ fromList [42] @-law> 'Relude.length' ('one' @('Set' a) x) ≡ 1+law> 'Relude.Foldable.Reexport.length' ('one' @('Set' a) x) ≡ 1 @ -} instance One (Set a) where@@ -282,7 +285,7 @@ fromList [42] @-law> 'Relude.length' ('one' @('HashSet' a) x) ≡ 1+law> 'Relude.Foldable.Reexport.length' ('one' @('HashSet' a) x) ≡ 1 @ -} instance Hashable a => One (HashSet a) where
src/Relude/Container/Reexport.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Trustworthy #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Container.Reexport+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Reexports container-related data types, functions and typeclasses from @base@, @containers@ and @unordered-containers@ packages.
src/Relude/Debug.hs view
@@ -1,33 +1,44 @@ {-# LANGUAGE CPP #-}++#if __GLASGOW_HASKELL__ >= 902+{-# OPTIONS_GHC -Wno-operator-whitespace #-}+#endif+ {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE TypeFamilies #-}+#if ( __GLASGOW_HASKELL__ < 906 ) {-# LANGUAGE TypeInType #-}+#endif {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} -#if __GLASGOW_HASKELL__ > 802-{-# LANGUAGE DerivingStrategies #-}-#endif- {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Debug+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable -Functions for debugging and prototyping. If you leave these functions in your-code then a warning is generated to remind you about left usages.+This module contains functions for debugging __pure__ functions. You+can't use functions like 'System.IO.putStrLn' for this purpose because+they require changes to the type signature, but functions in this module+avoid this problem by being pure on their own. +Additionally, these functions produce compile-time warnings, if you leave them+in your code. Warnings help you to cleanup all debugging usages before+releasing.+ @ __ghci>__ foo = trace "I forgot trace in code" @@ -36,18 +47,43 @@ "'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.+The following table briefly shows names and types of all functions in+this module.+++-----------------+----------------------------------------++| __Name__ | __Type__ |++=================+========================================++| 'trace' | @String -> a -> a@ |++-----------------+----------------------------------------++| 'traceShow' | @Show a => a -> b -> b@ |++-----------------+----------------------------------------++| 'traceShowId' | @Show a => a -> a@ |++-----------------+----------------------------------------++| 'traceShowWith' | @Show b => (a -> b) -> a -> a@ |++-----------------+----------------------------------------++| 'traceId' | @String -> String@ |++-----------------+----------------------------------------++| 'traceM' | @(Applicative f) => String -> f ()@ |++-----------------+----------------------------------------++| 'traceShowM' | @(Show a, Applicative f) => a -> f ()@ |++-----------------+----------------------------------------+++__⚠ NOTE:__ Use these functions only for local debugging+purposes. They break referential transparency, they are only useful+when you want to observe intermediate values of your pure functions+and to understand the behaviour locally. If you want to log debug+messages in your application, consider using a logging library+instead. -} module Relude.Debug ( -- * Tracing trace- , traceM- , traceId , traceShow , traceShowId+ , traceShowWith+ , traceId+ , traceM , traceShowM -- * Imprecise error@@ -57,12 +93,15 @@ ) where import Data.Data (Data)+#if __GLASGOW_HASKELL__ >= 904+import Data.Type.Equality (type (~))+#endif import GHC.Exts (RuntimeRep, TYPE) import GHC.TypeLits (ErrorMessage (..), TypeError) import Relude.Applicative (Applicative)-import Relude.Base (Bounded, Char, Constraint, Enum, Eq, Generic, HasCallStack, Ord, Show, Type,- Typeable)+import Relude.Base (Char, Constraint, Eq, Generic, HasCallStack, Ord, Show, Type, Typeable)+import Relude.Enum (Bounded, Enum) import Relude.String (Read, String, Text, toString) import qualified Debug.Trace as Debug@@ -77,7 +116,8 @@ -- trace ---------------------------------------------------------------------------- -{- | Version of 'Debug.Trace.trace' that leaves warning.+{- | Prints the given 'String' message and returns the passed value of+type @a@. >>> increment l = map (+1) l >>> increment [2, 3, 4]@@ -88,12 +128,17 @@ incrementing each value of: [2,3,4] [3,4,5] +* If you want to print a 'Show'able value instead of 'String', use 'traceShow'.+* If you want to print the value itself, use 'traceShowId'.+* If you want to print by specifying a custom formatting function, use 'traceShowWith'.+ -} trace :: String -> a -> a trace = Debug.trace {-# WARNING trace "'trace' remains in code" #-} -{- | Version of 'Debug.Trace.traceShow' that leaves warning.+{- | Similar to 'trace' but prints a given value with the 'Show'+instance instead of a 'String'. >>> increment l = map (+1) l >>> increment [2, 3, 4]@@ -104,24 +149,55 @@ [2,3,4] [3,4,5] +* If you want to print a specific 'String' instead, use 'trace'+* If you want to print and return the same value, use 'traceShowId'+* If you want to specify a custom printing function, use 'traceShowWith' -} traceShow :: Show a => a -> b -> b traceShow = Debug.traceShow {-# WARNING traceShow "'traceShow' remains in code" #-} -{- | Version of 'Debug.Trace.traceShowId' that leaves warning.+{- | Similar to 'traceShow' but prints the given value itself instead+of a separate value. >>> traceShowId (1+2+3, "hello" ++ "world") (6,"helloworld") (6,"helloworld") +* If you to specify a different value to print, use 'trace' or 'traceShow'+* If you want to have more control over printing, use 'traceShowWith' -} traceShowId :: Show a => a -> a traceShowId = Debug.traceShowId {-# WARNING traceShowId "'traceShowId' remains in code" #-} -{- | Version of 'Debug.Trace.traceM' that leaves warning.+{- | Similar 'traceShowId', but uses a provided function to convert the+argument to a value with the 'Show' constraint. +>>> traceShowWith fst (1, "ABC")+1+(1,"ABC")++In other words, @'traceShowId' ≡ 'traceShowWith' id@.++This function is useful for debugging values that do not have 'Show'+instance:++>>> fst $ traceShowWith fst (1, id)+1+1++* If you don't need such flexibility, use simpler 'trace', 'traceShow' or 'traceShowId'++@since 1.0.0.0+-}+traceShowWith :: Show b => (a -> b) -> a -> a+traceShowWith f v = Debug.traceShow (f v) v+{-# WARNING traceShowWith "'traceShowWith remains in code" #-}++{- | Trace function to print values while working a pure monad+(e.g. 'Maybe', 'State', etc.)+ >>> :{ let action :: Maybe Int action = do@@ -135,13 +211,15 @@ x: 3 y: 12 Just 18++* If you want to print a value with the 'Show' instance instead, use 'traceShowM' -} traceM :: (Applicative f) => String -> f () traceM = Debug.traceM {-# WARNING traceM "'traceM' remains in code" #-} {-|-Like 'traceM', but uses 'Relude.show' on the argument to convert it to a+Like 'traceM', but uses 'Prelude.show' on the argument to convert it to a 'String'. >>> :{@@ -162,7 +240,7 @@ traceShowM = Debug.traceShowM {-# WARNING traceShowM "'traceShowM' remains in code" #-} -{- | Version of 'Debug.Trace.traceId' that leaves warning.+{- | Similar to 'traceShowId' but specialised for 'String'. >>> traceId "hello" "hello@@ -180,22 +258,9 @@ branch of code execution is not possible. __DO NOT USE__ 'error' as a normal error handling mechanism. -#ifdef mingw32_HOST_OS->>> error "oops"-*** Exception: oops-CallStack (from HasCallStack):- 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:218:11 in ...-...-#endif--⚠️__CAUTION__⚠️ Unlike "Prelude" version, 'error' takes 'Relude.Text' as an-argument. In case it used by mistake, the user will see the following:+⚠️__CAUTION__⚠️ Unlike "Prelude" version, 'error' takes+ t'Relude.String.Reexport.Text' as an argument. In case it used by mistake,+the user will see the following: >>> error ("oops" :: String) ...@@ -238,11 +303,7 @@ -- | 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,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.DeepSeq+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable This module contains useful functions to evaluate expressions to weak-head normal form (WHNF) or just normal form (NF). Useful to force traces or @error@s@@ -40,7 +41,7 @@ -- $setup -- >>> import Relude -{- | Lifted alias for 'Control.Exception.Base.evaluate' with clearer name.+{- | Lifted alias for 'Control.Exception.Base.evaluate' with a clearer name. >>> let list = [1..5] :: [Int] >>> :sprint list@@ -68,7 +69,7 @@ {-# INLINE evaluateWHNF_ #-} {-# SPECIALIZE evaluateWHNF_ :: a -> IO () #-} -{- | Alias for @evaluateWHNF . force@ with clearer name.+{- | Alias for @evaluateWHNF . force@ with a clearer name. >>> let list = [1..5] :: [Int] >>> :sprint list@@ -83,7 +84,7 @@ {-# SPECIALIZE evaluateNF :: NFData a => a -> IO a #-} {- | Alias for @evaluateWHNF . rnf@. Similar to 'evaluateNF'--- but discards resulting value.+but discards the resulting value. >>> let list = [1..5] :: [Int] >>> :sprint list
+ src/Relude/Enum.hs view
@@ -0,0 +1,149 @@+{-# LANGUAGE Safe #-}++{- |+Module : Relude.Enum+Copyright : (c) 2021-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable++Reexports 'Enum' related typeclasses and functions. Also introduces a few useful+helpers to work with Enums.++__Note:__ 'universe', 'universeNonEmpty' and 'inverseMap' were previously in the+extra modules, but due to their benefit in different use cases. If you imported+@Relude.Extra.Enum@ module, you can remove it now, as these functions are+reexported in the main "Relude" module.++@since 1.0.0.0+-}++module Relude.Enum+ ( -- * Useful combinators for Enums+ universe+ , universeNonEmpty+ , inverseMap+ -- * Base reexports+ , module GHC.Enum+ ) where++import GHC.Enum (Bounded (..), Enum (..), boundedEnumFrom, boundedEnumFromThen)+import Data.List.NonEmpty (NonEmpty (..))+import Data.List (drop)+import Data.Maybe (Maybe (..))++import Relude.Base (Ord (..))+import Relude.Extra.Tuple (fmapToFst)++import qualified Data.Map.Strict as M+++-- $setup+-- >>> import Relude++{- | 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]++>>> 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) => NonEmpty a+universeNonEmpty = minBound :| drop 1 universe+{-# 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+shared for every call.++__Memory usage note:__ don't inverse functions that have types like 'Int'+as their input. In this case the created 'M.Map' will have huge size.++The complexity of reversed mapping is \(\mathcal{O}(\log n)\).++__Performance note:__ make sure to specialize monomorphic type of your functions+that use 'inverseMap' to avoid 'M.Map' reconstruction.++One of the common 'inverseMap' use-case is inverting the 'show' or a 'show'-like+function.++>>> data Color = Red | Green | Blue deriving (Show, Enum, Bounded)+>>> parse = inverseMap show :: String -> Maybe Color+>>> parse "Red"+Just Red+>>> parse "Black"+Nothing++__Correctness note:__ 'inverseMap' expects /injective function/ as its argument,+i.e. the function must map distinct arguments to distinct values.++Typical usage of this function looks like this:++@+__data__ GhcVer+ = Ghc802+ | Ghc822+ | Ghc844+ | Ghc865+ | Ghc881+ __deriving__ ('Eq', 'Ord', 'Show', 'Enum', 'Bounded')++showGhcVer :: GhcVer -> 'Text'+showGhcVer = \\__case__+ Ghc802 -> "8.0.2"+ Ghc822 -> "8.2.2"+ Ghc844 -> "8.4.4"+ Ghc865 -> "8.6.5"+ Ghc881 -> "8.8.1"++parseGhcVer :: 'Text' -> 'Maybe' GhcVer+parseGhcVer = 'inverseMap' showGhcVer+@++@since 0.1.1+-}+inverseMap+ :: forall a k .+ (Bounded a, Enum a, Ord k)+ => (a -> k)+ -> (k -> Maybe a)+inverseMap f = \k -> M.lookup k dict+ where+ dict :: M.Map k a+ dict = M.fromList (fmapToFst f (universe @a))+{-# INLINE inverseMap #-}
src/Relude/Exception.hs view
@@ -1,21 +1,18 @@-{-# LANGUAGE CPP #-}+{-# LANGUAGE DerivingStrategies #-} {-# 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-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Exception+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+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.@@ -47,15 +44,12 @@ 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"- ++ prettyCallStack cStack+ displayException (Bug e cStack) =+ E.displayException e ++ "\n"+ ++ prettyCallStack cStack -- | Generate a pure value which, when forced, will throw the given exception impureThrow :: Exception e => e -> a
src/Relude/Extra.hs view
@@ -1,9 +1,10 @@ {- |-Copyright: (c) 2019-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra+Copyright : (c) 2019-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable This module exports all extra-related stuff. The extra modules are not exported by default, but you can easily bring them to@@ -33,8 +34,6 @@ -- $Tuple , module Relude.Extra.Type -- $Type- , module Relude.Extra.Validation- -- $Validation ) where import Relude.Extra.Bifunctor@@ -48,30 +47,30 @@ import Relude.Extra.Newtype import Relude.Extra.Tuple import Relude.Extra.Type-import Relude.Extra.Validation {- $Bifunctor-Additional combinators for 'Relude.Bifunctor'.+Additional combinators for t'Relude.Functor.Reexport.Bifunctor'. -} {- $CallStack-Useful functions to extract information from 'Relude.CallStack'.+Useful functions to extract information from t'Relude.Base.CallStack'. -} {- $Enum-Extra utilities for types that implement 'Relude.Bounded' and 'Relude.Enum'+Extra utilities for types that implement t'Relude.Enum.Bounded' and t'Relude.Enum.Enum' constraints. -} {- $Foldable-Extra folds for instances of the 'Relude.Foldable' typeclass.+Extra folds for instances of the t'Relude.Foldable.Reexport.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' is a typeclass like t'Relude.Foldable.Reexport.Foldable' but for non-empty+structures. For example, t'Relude.List.NonEmpty.NonEmpty',+'Relude.Functor.Reexport.Identity'. 'Foldable1' has all type-safe and total methods like `head1`, `maximum1` in-contradiction with 'Data.Foldable.Foldable'.+contradiction with t'Relude.Foldable.Reexport.Foldable'. -} {- $Group@@ -96,12 +95,4 @@ {- $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,11 +1,12 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Bifunctor+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Useful combinators for bifunctors inside functors. This set of functions is useful when you want to work with types like these ones:
src/Relude/Extra/CallStack.hs view
@@ -1,11 +1,12 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.CallStack+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Contains useful functions to work with GHC callstack.
src/Relude/Extra/Enum.hs view
@@ -1,11 +1,12 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Enum+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Mini @bounded-enum@ framework inside @relude@. @@ -13,128 +14,14 @@ -} module Relude.Extra.Enum- ( universe- , universeNonEmpty- , inverseMap- , next+ ( next , prev , safeToEnum ) where import Relude-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]-->>> 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-shared for every call.--__Memory usage note:__ don't inverse functions that have types like 'Int'-as their result. In this case the created 'M.Map' will have huge size.--The complexity of reversed mapping is \(\mathcal{O}(\log n)\).--__Performance note:__ make sure to specialize monomorphic type of your functions-that use 'inverseMap' to avoid 'M.Map' reconstruction.--One of the common 'inverseMap' use-case is inverting the 'show' or a 'show'-like-function.-->>> data Color = Red | Green | Blue deriving (Show, Enum, Bounded)->>> parse = inverseMap show :: String -> Maybe Color->>> parse "Red"-Just Red->>> parse "Black"-Nothing--__Correctness note:__ 'inverseMap' expects /injective function/ as its argument,-i.e. the function must map distinct arguments to distinct values.--Typical usage of this function looks like this:--@-__data__ GhcVer- = Ghc802- | Ghc822- | Ghc844- | Ghc865- | Ghc881- __deriving__ ('Eq', 'Ord', 'Show', 'Enum', 'Bounded')--showGhcVer :: GhcVer -> 'Text'-showGhcVer = \\__case__- Ghc802 -> "8.0.2"- Ghc822 -> "8.2.2"- Ghc844 -> "8.4.4"- Ghc865 -> "8.6.5"- Ghc881 -> "8.8.1"--parseGhcVer :: 'Text' -> 'Maybe' GhcVer-parseGhcVer = 'inverseMap' showGhcVer-@--@since 0.1.1--}-inverseMap- :: forall a k .- (Bounded a, Enum a, Ord k)- => (a -> k)- -> (k -> Maybe a)-inverseMap f = \k -> M.lookup k dict- where- dict :: M.Map k a- dict = M.fromList $ fmapToFst f (universe @a)-{-# INLINE inverseMap #-}- {- | Like 'succ', but doesn't fail on 'maxBound'. Instead it returns 'minBound'. >>> next False@@ -154,10 +41,10 @@ {- | Like 'pred', but doesn't fail on 'minBound'. Instead it returns 'maxBound'. ->>> prev False-True >>> prev True False+>>> prev False+True >>> pred False *** Exception: Prelude.Enum.Bool.pred: bad argument
src/Relude/Extra/Foldable.hs view
@@ -1,11 +1,13 @@ {-# LANGUAGE Safe #-}+{-# LANGUAGE BangPatterns #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Foldable+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Contains utility functions for working with tuples. @@ -14,11 +16,14 @@ module Relude.Extra.Foldable ( foldlSC+ , average ) where import Relude +-- $setup+ {- | A left-associative fold that's tail-recursive but can still short-circuit. Returning a 'Left' short-circuits and immediately returns the value inside. Returning a 'Right' continues the fold as usual with the value inside.@@ -38,3 +43,26 @@ Left l -> l Right r -> k r {-# INLINE foldlSC #-}++{- | Given a 'Foldable' of 'Fractional' elements, computes the average if+possible and returns 'Maybe' element.++>>> average [42]+Just 42.0+>>> average @Double [1, 2, 3, 4]+Just 2.5+>>> average @Float [1.5, 2.5, 3 ,4]+Just 2.75+>>> average []+Nothing++@since 1.0.0.0+-}+average :: forall a f . (Foldable f, Fractional a) => f a -> Maybe a+average xs+ | null xs = Nothing+ | otherwise = Just+ . uncurry (/)+ . foldl' (\(!total, !count) x -> (total + x, count + 1)) (0,0)+ $ xs+{-# INLINE average #-}
src/Relude/Extra/Foldable1.hs view
@@ -1,5 +1,12 @@ {-# OPTIONS_GHC -Wno-redundant-constraints #-} +{-# LANGUAGE CPP #-}++#if __GLASGOW_HASKELL__ >= 902+{-# OPTIONS_GHC -Wno-operator-whitespace #-}+#endif++{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE Safe #-} {-# LANGUAGE TypeFamilies #-}@@ -7,12 +14,13 @@ {-# LANGUAGE UndecidableInstances #-} {- |-Copyright: (c) 2011-2015 Edward Kmett- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Foldable1+Copyright : (c) 2011-2015 Edward Kmett+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable 'Foldable1' is a typeclass like 'Data.Foldable.Foldable' but for non-empty structures. For example, 'Relude.NonEmpty', 'Relude.Identity'.@@ -26,10 +34,11 @@ module Relude.Extra.Foldable1 ( Foldable1 (..) , foldl1'+ , average1 ) where import Relude hiding (Product (..), Sum (..))-import Relude.Extra.Newtype (( #. ))+import Relude.Extra.Newtype ((#.)) import Data.Functor.Product (Product (..)) import Data.Functor.Sum (Sum (..))@@ -67,13 +76,26 @@ fold1 :: Semigroup m => f m -> m fold1 = foldMap1 id + {- | Combines the elements of a non-empty structure using a binary function @f@.++ >>> foldr1 (+) 0 (1 :| [2, 3])+ 6+ >>> foldr1 (+) 1 $ Identity 3+ 4++ @since 1.0.0.0+ -}+ foldr1 :: (a -> b -> b) -> b -> f a -> b+ foldr1 f accum as = appEndo (foldMap1 (Endo #. f) as) accum+ {-# INLINE foldr1 #-}+ {- | Convert a non-empty data structure to a NonEmpty list. >>> toNonEmpty (Identity 2) 2 :| [] -} toNonEmpty :: f a -> NonEmpty a- toNonEmpty = foldMap1 (:|[])+ toNonEmpty = foldMap1 (:| []) {- | The first element of a non-empty data structure. @@ -107,6 +129,30 @@ minimum1 :: Ord a => f a -> a minimum1 = SG.getMin #. foldMap1 SG.Min + {- | The largest element of a non-empty data structure+ with respect to the given comparison function.++ >>> maximumOn1 abs (0 :| [2, 1, -3, -2])+ -3++ @since 1.0.0.0+ -}+ maximumOn1 :: Ord b => (a -> b) -> f a -> a+ maximumOn1 f = maximumOn1 f . toNonEmpty+ {-# INLINE maximumOn1 #-}++ {- | The smallest element of a non-empty data structure+ with respect to the given comparison function.++ >>> minimumOn1 abs (0 :| [2, 1, -3, -2])+ 0++ @since 1.0.0.0+ -}+ minimumOn1 :: Ord b => (a -> b) -> f a -> a+ minimumOn1 f = minimumOn1 f . toNonEmpty+ {-# INLINE minimumOn1 #-}+ {- | @since 0.3.0@@ -139,6 +185,24 @@ {-# INLINE maximum1 #-} {-# INLINE minimum1 #-} + maximumOn1 :: forall a b. Ord b => (a -> b) -> NonEmpty a -> a+ maximumOn1 func = foldl1' $ cmpOn+ where+ cmpOn :: a -> a -> a+ cmpOn a b = case func a `compare` func b of+ GT -> a+ _ -> b+ {-# INLINE maximumOn1 #-}++ minimumOn1 :: forall a b. Ord b => (a -> b) -> NonEmpty a -> a+ minimumOn1 func = foldl1' $ cmpOn+ where+ cmpOn :: a -> a -> a+ cmpOn a b = case func a `compare` func b of+ LT -> a+ _ -> b+ {-# INLINE minimumOn1 #-}+ {- | @since 0.3.0@@ -153,7 +217,7 @@ {-# INLINE fold1 #-} toNonEmpty :: Identity a -> NonEmpty a- toNonEmpty = (:|[]) . coerce+ toNonEmpty = (:| []) . coerce {-# INLINE toNonEmpty #-} head1 :: Identity a -> a@@ -172,6 +236,14 @@ minimum1 = coerce {-# INLINE minimum1 #-} + maximumOn1 :: Ord b => (a -> b) -> Identity a -> a+ maximumOn1 = const coerce+ {-# INLINE maximumOn1 #-}++ minimumOn1 :: Ord b => (a -> b) -> Identity a -> a+ minimumOn1 = const coerce+ {-# INLINE minimumOn1 #-}+ {- | @since 0.3.0@@ -186,7 +258,7 @@ {-# INLINE fold1 #-} toNonEmpty :: (c, a) -> NonEmpty a- toNonEmpty (_, y) = (y :| [])+ toNonEmpty (_, y) = y :| [] {-# INLINE toNonEmpty #-} head1, last1 :: (c, a) -> a@@ -201,6 +273,12 @@ {-# INLINE maximum1 #-} {-# INLINE minimum1 #-} + maximumOn1, minimumOn1 :: Ord b => (a -> b) -> (c, a) -> a+ maximumOn1 = const snd+ minimumOn1 = const snd+ {-# INLINE maximumOn1 #-}+ {-# INLINE minimumOn1 #-}+ {- | @since 0.3.0@@ -279,6 +357,9 @@ foldMap1 :: Semigroup m => (a -> m) -> [a] -> m foldMap1 _ _ = error "Unreachable list instance of Foldable1" + foldr1 :: (Foldable1 f) => (a -> b -> b) -> b -> f a -> b+ foldr1 _ _ = error "Unreachable list instance of Foldable1"+ fold1 :: Semigroup m => [m] -> m fold1 _ = error "Unreachable list instance of Foldable1" @@ -297,6 +378,12 @@ minimum1 :: Ord a => [a] -> a minimum1 _ = error "Unreachable list instance of Foldable1" + maximumOn1 :: (Ord b, Foldable1 f) => (a -> b) -> f a -> a+ maximumOn1 _ _ = error "Unreachable list instance of Foldable1"++ minimumOn1 :: (Ord b, Foldable1 f) => (a -> b) -> f a -> a+ minimumOn1 _ _ = error "Unreachable list instance of Foldable1"+ {- | Strictly folds non-empty structure with given function @f@: @@@ -312,3 +399,47 @@ foldl1' _ (x :| []) = x foldl1' f (x :| (y:ys)) = foldl' f (f x y) ys {-# INLINE foldl1' #-}++{- | Given a 'Foldable1' of 'Fractional' elements, computes the average if+possible and returns the resulting element.+++>>> average1 (42 :| [])+42.0+>>> average1 (1 :| [2,3,4])+2.5++@since 1.0.0.0+-}+average1 :: forall a f . (Foldable1 f, Fractional a) => f a -> a+average1 = uncurry (/) . foldl' (\(!total, !count) x -> (total + x, count + 1)) (0, 0)+{-# INLINE average1 #-}++{-+Copyright 2011-2015 Edward Kmett++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions+are met:++1. Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.++THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,+STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN+ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+POSSIBILITY OF SUCH DAMAGE.+-}
src/Relude/Extra/Group.hs view
@@ -1,12 +1,14 @@-{-# LANGUAGE Safe #-}-{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE Safe #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Group+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Polymorphic grouping functions.
src/Relude/Extra/Lens.hs view
@@ -2,12 +2,13 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2013-2016 Edward Kmett- (c) 2019-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Lens+Copyright : (c) 2012-2016 Edward Kmett+ (c) 2019-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable @since 0.5.0 @@ -158,7 +159,6 @@ - [lens](https://hackage.haskell.org/package/lens) - [microlens](https://hackage.haskell.org/package/microlens) - [lens tutorial](http://hackage.haskell.org/package/lens-tutorial-1.0.3/docs/Control-Lens-Tutorial.html)- -} module Relude.Extra.Lens@@ -244,3 +244,33 @@ (%~) :: Lens' s a -> (a -> a) -> s -> s (%~) = over {-# INLINE (%~) #-}+++{-+Copyright 2012-2016 Edward Kmett++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions+are met:++1. Redistributions of source code must retain the above copyright+ notice, this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright+ notice, this list of conditions and the following disclaimer in the+ documentation and/or other materials provided with the distribution.++THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,+STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN+ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+POSSIBILITY OF SUCH DAMAGE.+-}
src/Relude/Extra/Map.hs view
@@ -1,12 +1,15 @@-{-# LANGUAGE Trustworthy #-}-{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Map+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Contains implementation of polymorphic type classes for data types 'Set' and 'Map'.@@ -25,9 +28,17 @@ , elems ) where +#if __GLASGOW_HASKELL__ >= 904+import Data.Type.Equality (type (~))+#endif import GHC.Exts (IsList (Item, toList)) +#if MIN_VERSION_hashable(1,4,0)+import Relude.Base (Ord, Type)+#else import Relude.Base (Eq, Ord, Type)+#endif+ import Relude.Bool (Bool, guard, not) import Relude.Container.Reexport (HashMap, HashSet, Hashable, IntMap, IntSet, Map, Set, fst, snd) import Relude.Function ((.))@@ -79,7 +90,11 @@ @since 0.1.0 -}+#if MIN_VERSION_hashable(1,4,0)+instance (Hashable k) => StaticMap (HashMap k v) where+#else instance (Eq k, Hashable k) => StaticMap (HashMap k v) where+#endif type Key (HashMap k v) = k type Val (HashMap k v) = v @@ -124,7 +139,11 @@ @since 0.1.0 -}+#if MIN_VERSION_hashable(1,4,0)+instance (Hashable a) => StaticMap (HashSet a) where+#else instance (Eq a, Hashable a) => StaticMap (HashSet a) where+#endif type Key (HashSet a) = a type Val (HashSet a) = a @@ -236,7 +255,11 @@ @since 0.1.0 -}+#if MIN_VERSION_hashable(1,4,0)+instance (Hashable k) => DynamicMap (HashMap k v) where+#else instance (Eq k, Hashable k) => DynamicMap (HashMap k v) where+#endif insert = HM.insert {-# INLINE insert #-} insertWith = HM.insertWith
src/Relude/Extra/Newtype.hs view
@@ -1,12 +1,12 @@-{-# LANGUAGE CPP #-} {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Newtype+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Functions to ease work with @newtypes@. @@ -18,9 +18,7 @@ , wrap , under , under2-#if ( __GLASGOW_HASKELL__ != 802 ) , underF2-#endif , (#.) ) where @@ -88,7 +86,6 @@ under2 = coerce {-# INLINE under2 #-} -#if ( __GLASGOW_HASKELL__ != 802 ) {- | Version of 'under2' that works on @newtype@s parametrized by their representation. Provided for convenience. @@ -102,7 +99,6 @@ underF2 :: forall n a . Coercible a (n a) => (n a -> n a -> n a) -> (a -> a -> a) underF2 = coerce {-# INLINE underF2 #-}-#endif {- | Coercible composition. This function allows to write more efficient implementations of function compositions over @newtypes@.
src/Relude/Extra/Tuple.hs view
@@ -2,11 +2,12 @@ {-# LANGUAGE TupleSections #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Tuple+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Contains utility functions for working with tuples. @@ -26,9 +27,14 @@ , traverseBoth ) where -import Relude+import Relude.Function ((.))+import Relude.Functor (Functor (..), (<$>))+import Relude.Applicative (Applicative (..)) +-- $setup+-- >>> import Relude+ {- | Creates a tuple by pairing something with itself. >>> dup "foo"@@ -113,7 +119,7 @@ mapToFst :: (a -> b) -> a -> (b, a) mapToFst = toFst {-# INLINE mapToFst #-}-{-# DEPRECATED mapToFst "Use 'toFst' from 'Relude.Extra.Tuple' instead" #-}+{-# DEPRECATED mapToFst "Use 'toFst' from [Tuple](\"Relude.Extra.Tuple\") instead" #-} {- | Apply a function, with the result in the second slot, and the value in the other.@@ -128,7 +134,7 @@ mapToSnd :: (a -> b) -> a -> (a, b) mapToSnd = toSnd {-# INLINE mapToSnd #-}-{-# DEPRECATED mapToSnd "Use 'toSnd' from 'Relude.Extra.Tuple' instead" #-}+{-# DEPRECATED mapToSnd "Use 'toSnd' from [Tuple](\"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,
src/Relude/Extra/Type.hs view
@@ -9,11 +9,12 @@ {-# LANGUAGE UndecidableInstances #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Experimental-Portability: Portable+Module : Relude.Extra.Type+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Contains useful utilities to work with Types. @@ -31,15 +32,17 @@ import Relude -#if ( __GLASGOW_HASKELL__ >= 802 ) import Type.Reflection (typeRep)-#else-import Data.Typeable (typeRep)-#endif +#if ( __GLASGOW_HASKELL__ >= 906 ) -- $setup--- >>> :set -XDataKinds -XTypeOperators+-- >>> :set -XAllowAmbiguousTypes -XDataKinds -XExplicitNamespaces -XPolyKinds -XTypeFamilies -XTypeOperators -XUndecidableInstances+-- >>> :set -fprint-redundant-promotion-ticks+#else+-- $setup+-- >>> :set -XAllowAmbiguousTypes -XDataKinds -XExplicitNamespaces -XPolyKinds -XTypeFamilies -XTypeOperators -XUndecidableInstances+#endif {- | Gets a string representation of a type. @@ -57,16 +60,23 @@ @since 0.4.0 -} typeName :: forall a. Typeable a => Text-#if ( __GLASGOW_HASKELL__ >= 802 ) typeName = show (typeRep @a)-#else-typeName = show (typeRep (Proxy @a))-#endif {-# INLINE typeName #-} {- | Concatenates type-level lists. -#if ( __GLASGOW_HASKELL__ >= 806 )+#if ( __GLASGOW_HASKELL__ >= 902 )++>>> :kind! '[ 'Just 5, 'Nothing] ++ '[ 'Just 3, 'Nothing, 'Just 1]+'[ 'Just 5, 'Nothing] ++ '[ 'Just 3, 'Nothing, 'Just 1] :: [Maybe+ Natural]+= '[ 'Just 5, 'Nothing, 'Just 3, 'Nothing, 'Just 1]++>>> :kind! '[] ++ '[ 'Just 3, 'Nothing, 'Just 1]+'[] ++ '[ 'Just 3, 'Nothing, 'Just 1] :: [Maybe Natural]+= '[ 'Just 3, 'Nothing, 'Just 1]++#elif ( __GLASGOW_HASKELL__ >= 806 ) >>> :kind! '[ 'Just 5, 'Nothing] ++ '[ 'Just 3, 'Nothing, 'Just 1] '[ 'Just 5, 'Nothing] ++ '[ 'Just 3, 'Nothing, 'Just 1] :: [Maybe
− src/Relude/Extra/Validation.hs
@@ -1,432 +0,0 @@-{-# 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-2020 Kowainik-SPDX-License-Identifier: MIT-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-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.-2. Performing multiple validations of a single value.--Instances of different standard typeclasses provide various semantics:--1. 'Functor': change the type inside 'Success'.-2. 'Bifunctor': change both 'Failure' and 'Success'.-3. 'Applicative': apply function to values inside 'Success' and accumulate- errors inside 'Failure'.-4. 'Semigroup': accumulate both 'Failure' and 'Success' with '<>'.-5. 'Monoid': 'Success' that shores 'mempty'.-6. 'Alternative': return first 'Success' or accumulate all errors inside 'Failure'.--}--module Relude.Extra.Validation- ( -- * How to use- -- $use- Validation(..)- , validationToEither- , eitherToValidation- ) where--import GHC.TypeLits (ErrorMessage (..), TypeError)--import Relude---- >>> $setup--- >>> import Relude--{- $use--Take for example a type @Computer@ that needs to be validated:-->>> :{-data Computer = Computer- { computerRam :: !Int -- ^ Ram in Gigabytes- , computerCpus :: !Int- } deriving (Eq, Show)-:}--You can validate that the computer has a minimum of 16GB of RAM:-->>> :{-validateRam :: Int -> Validation [Text] Int-validateRam ram- | ram >= 16 = Success ram- | otherwise = Failure ["Not enough RAM"]-:}--and that the processor has at least two CPUs:-->>> :{-validateCpus :: Int -> Validation [Text] Int-validateCpus cpus- | cpus >= 2 = Success cpus- | otherwise = Failure ["Not enough CPUs"]-:}--You can use these functions with the 'Applicative' instance of the 'Validation'-type to construct a validated @Computer@. You will get either (pun intended) a-valid @Computer@ or the errors that prevent it from being considered valid.--Like so:-->>> :{-mkComputer :: Int -> Int -> Validation [Text] Computer-mkComputer ram cpus = Computer- <$> validateRam ram- <*> validateCpus cpus-:}--Using @mkComputer@ we get a @Success Computer@ or a list with all possible errors:-->>> mkComputer 16 2-Success (Computer {computerRam = 16, computerCpus = 2})-->>> mkComputer 16 1-Failure ["Not enough CPUs"]-->>> mkComputer 15 2-Failure ["Not enough RAM"]-->>> mkComputer 15 1-Failure ["Not enough RAM","Not enough CPUs"]--}---- | 'Validation' is 'Either' with a 'Left' that is a 'Semigroup'.-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- fmap _ (Failure e) = Failure e- fmap f (Success a) = Success (f a)- {-# INLINE fmap #-}-- (<$) :: a -> Validation e b -> Validation e a- x <$ Success _ = Success x- _ <$ Failure e = Failure e- {-# INLINE (<$) #-}--{- | This instances covers the following cases:--1. Both 'Success': combine values inside 'Success' with '<>'.-2. Both 'Failure': combine values inside 'Failure' with '<>'.-3. One 'Success', one 'Failure': return 'Failure'.--__Examples__-->>> success1 = Success [42] :: Validation [Text] [Int]->>> success2 = Success [69] :: Validation [Text] [Int]->>> failure1 = Failure ["WRONG"] :: Validation [Text] [Int]->>> failure2 = Failure ["FAIL"] :: Validation [Text] [Int]-->>> success1 <> success2-Success [42,69]-->>> failure1 <> failure2-Failure ["WRONG","FAIL"]-->>> success1 <> failure1-Failure ["WRONG"]--@since 0.6.0.0--}-instance (Semigroup e, Semigroup a) => Semigroup (Validation e a) where- (<>) :: Validation e a -> Validation e a -> Validation e a- (<>) = liftA2 (<>)- {-# INLINE (<>) #-}--{- | 'mempty' is @'Success' 'mempty'@.--@since 0.6.0.0--}-instance (Semigroup e, Semigroup a, Monoid a) => Monoid (Validation e a) where- mempty :: Validation e a- mempty = Success mempty- {-# INLINE mempty #-}-- 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.--__Examples__-->>> success1 = Success 42 :: Validation [Text] Int->>> success2 = Success 69 :: Validation [Text] Int->>> successF = Success (* 2) :: Validation [Text] (Int -> Int)->>> failure1 = Failure ["WRONG"] :: Validation [Text] Int->>> failure2 = Failure ["FAIL"] :: Validation [Text] Int-->>> successF <*> success1-Success 84-->>> successF <*> failure1-Failure ["WRONG"]-->>> (+) <$> success1 <*> success2-Success 111-->>> (+) <$> failure1 <*> failure2-Failure ["WRONG","FAIL"]-->>> liftA2 (+) success1 failure1-Failure ["WRONG"]-->>> liftA3 (,,) failure1 success1 failure2-Failure ["WRONG","FAIL"]--Implementations of all functions are lazy and they correctly work if some-arguments are not fully evaluated.-->>> :{-isFailure :: Validation e a -> Bool-isFailure (Failure _) = True-isFailure (Success _) = False-:}-->>> failure1 *> failure2-Failure ["WRONG","FAIL"]->>> isFailure $ failure1 *> failure2-True->>> epicFail = error "Impossible validation" :: Validation [Text] Int->>> isFailure $ failure1 *> epicFail-True--}-instance Semigroup e => Applicative (Validation e) where- pure :: a -> Validation e a- pure = Success- {-# INLINE pure #-}-- (<*>) :: Validation e (a -> b) -> Validation e a -> Validation e b- Failure e <*> b = Failure $ case b of- Failure e' -> e <> e'- Success _ -> e- Success _ <*> Failure e = Failure e- Success f <*> Success a = Success (f a)- {-# INLINE (<*>) #-}-- (*>) :: Validation e a -> Validation e b -> Validation e b- Failure e *> b = Failure $ case b of- Failure e' -> e <> e'- Success _ -> e- Success _ *> Failure e = Failure e- Success _ *> Success b = Success b- {-# INLINE (*>) #-}-- (<*) :: Validation e a -> Validation e b -> Validation e a- Failure e <* b = Failure $ case b of- Failure e' -> e <> e'- Success _ -> e- Success _ <* Failure e = Failure e- Success a <* Success _ = Success a- {-# INLINE (<*) #-}---{- | This instance implements the following behavior for the binary operator:--1. Both 'Failure': combine values inside 'Failure' using '<>'.-2. At least is 'Success': return the left 'Success' (the earliest 'Success').-3. 'empty' is @'Failure' 'mempty'@.--__Examples__-->>> success1 = Success [42] :: Validation [Text] [Int]->>> success2 = Success [69] :: Validation [Text] [Int]->>> failure1 = Failure ["WRONG"] :: Validation [Text] [Int]->>> failure2 = Failure ["FAIL"] :: Validation [Text] [Int]-->>> success1 <|> success2-Success [42]->>> failure1 <|> failure2-Failure ["WRONG","FAIL"]->>> failure2 <|> success2-Success [69]--}-instance (Semigroup e, Monoid e) => Alternative (Validation e) where- empty :: Validation e a- empty = Failure mempty- {-# INLINE empty #-}-- (<|>) :: Validation e a -> Validation e a -> Validation e a- s@Success{} <|> _ = s- _ <|> s@Success{} = s- Failure e <|> Failure e' = Failure (e <> e')- {-# INLINE (<|>) #-}--instance Foldable (Validation e) where- fold :: Monoid m => Validation e m -> m- fold (Success a) = a- fold (Failure _) = mempty- {-# INLINE fold #-}-- foldMap :: Monoid m => (a -> m) -> Validation e a -> m- foldMap _ (Failure _) = mempty- foldMap f (Success a) = f a- {-# INLINE foldMap #-}-- foldr :: (a -> b -> b) -> b -> Validation e a -> b- foldr f x (Success a) = f a x- foldr _ x (Failure _) = x- {-# INLINE foldr #-}--instance Traversable (Validation e) where- traverse :: Applicative f => (a -> f b) -> Validation e a -> f (Validation e b)- traverse f (Success a) = Success <$> f a- traverse _ (Failure e) = pure (Failure e)- {-# INLINE traverse #-}-- sequenceA :: Applicative f => Validation e (f a) -> f (Validation e a)- sequenceA = traverse id- {-# INLINE sequenceA #-}--instance Bifunctor Validation where- bimap :: (e -> d) -> (a -> b) -> Validation e a -> Validation d b- bimap f _ (Failure e) = Failure (f e)- bimap _ g (Success a) = Success (g a)- {-# INLINE bimap #-}-- first :: (e -> d) -> Validation e a -> Validation d a- first f (Failure e) = Failure (f e)- first _ (Success a) = Success a- {-# INLINE first #-}-- second :: (a -> b) -> Validation e a -> Validation e b- second _ (Failure e) = Failure e- second g (Success a) = Success (g a)- {-# INLINE second #-}--#if MIN_VERSION_base(4,10,0)-instance Bifoldable Validation where- bifoldMap :: Monoid m => (e -> m) -> (a -> m) -> Validation e a -> m- bifoldMap f _ (Failure e) = f e- bifoldMap _ g (Success a) = g a- {-# INLINE bifoldMap #-}--instance Bitraversable Validation where- bitraverse :: Applicative f- => (e -> f d) -> (a -> f b) -> Validation e a -> f (Validation d b)- bitraverse f _ (Failure e) = Failure <$> f e- bitraverse _ g (Success a) = Success <$> g a- {-# INLINE bitraverse #-}-#endif--{- | Transform a 'Validation' into an 'Either'.-->>> validationToEither (Success "whoop")-Right "whoop"-->>> validationToEither (Failure "nahh")-Left "nahh"--}-validationToEither :: Validation e a -> Either e a-validationToEither = \case- Failure e -> Left e- Success a -> Right a-{-# INLINE validationToEither #-}-{-# DEPRECATED validationToEither "Use 'validationToEither' from 'validation-selective' instead"#-}--{- | Transform an 'Either' into a 'Validation'.-->>> eitherToValidation (Right "whoop")-Success "whoop"-->>> eitherToValidation (Left "nahh")-Failure "nahh"--}-eitherToValidation :: Either e a -> Validation e a-eitherToValidation = \case- Left e -> Failure e- Right a -> Success a-{-# INLINE eitherToValidation #-}-{-# DEPRECATED eitherToValidation "Use 'eitherToValidation' from 'validation-selective' instead"#-}--------------------------------------------------------------------------------- Custom errors-------------------------------------------------------------------------------{- | ⚠️__CAUTION__⚠️ This instance is for custom error display only.--It's not possible to implement lawful 'Monad' instance for 'Validation'.--In case it is used by mistake, the user will see the following:-->>> Success 42 >>= \n -> if even n then Success n else Failure ["Not even"]-...-... Type 'Validation' doesn't have lawful 'Monad' instance- which means that you can't use 'Monad' methods with 'Validation'.-...--@since 0.6.0.0--}-instance (NoValidationMonadError, Semigroup e) => Monad (Validation e) where- return = error "Unreachable Validation instance of Monad"- (>>=) = error "Unreachable Validation instance of Monad"---- | Helper type family to produce error messages-type family NoValidationMonadError :: Constraint where- NoValidationMonadError = TypeError- ( 'Text "Type 'Validation' doesn't have lawful 'Monad' instance"- ':$$: 'Text "which means that you can't use 'Monad' methods with 'Validation'."- )
src/Relude/File.hs view
@@ -1,11 +1,12 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.File+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Lifted to 'MonadIO' families of file processing functions for the 'Text', 'LText', 'ByteString' and 'LByteString' types.@@ -20,6 +21,15 @@ data with the help of functions from the "Relude.String.Conversion" module, e. g. 'Relude.String.Conversion.decodeUtf8'. +To be more precise, avoid the following functions:++* 'readFileText'+* 'readFileLText'++See the following blog post for more details:++* [Beware of readFile by Michael Snoyman](https://www.snoyman.com/blog/2016/12/beware-of-readfile/)+ @since 0.3.0 -} @@ -68,6 +78,7 @@ readFileText = liftIO . T.readFile {-# SPECIALIZE readFileText :: FilePath -> IO Text #-} {-# INLINE readFileText #-}+{-# WARNING readFileText ["'readFileText' depends on the system's locale settings and can throw unexpected exceptions.", "Use 'readFileBS' instead."] #-} {- | Lifted version of 'T.writeFile'. @@ -99,6 +110,7 @@ readFileLText = liftIO . LT.readFile {-# SPECIALIZE readFileLText :: FilePath -> IO LText #-} {-# INLINE readFileLText #-}+{-# WARNING readFileLText ["'readFileLText' depends on the system's locale settings and can throw unexpected exceptions.", "Use 'readFileLBS' instead."] #-} {- | Lifted version of 'LT.writeFile'.
src/Relude/Foldable.hs view
@@ -1,11 +1,12 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Foldable+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable This module provides 'Foldable' and 'Traversable' related types and functions. -}
src/Relude/Foldable/Fold.hs view
@@ -1,5 +1,11 @@ {-# OPTIONS_GHC -Wno-redundant-constraints #-} +{-# LANGUAGE CPP #-}++#if __GLASGOW_HASKELL__ >= 902+{-# OPTIONS_GHC -Wno-operator-whitespace #-}+#endif+ {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE Safe #-}@@ -8,17 +14,18 @@ {-# LANGUAGE UndecidableInstances #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Foldable.Fold+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Fixes and additions to 'Foldable'. Specifically: -* Space-leak free 'sum' and 'production'+* Space-leak free 'sum' and 'product' * 'elem' and 'notElem' are forbidden for 'Set' and 'HashSet' * Additional combinators for common idioms -}@@ -72,7 +79,7 @@ flipfoldl' f = foldl' (flip f) {-# INLINE flipfoldl' #-} -{- | Alternative version of @asum@.+{- | Alternative version of 'Relude.Foldable.Reexport.asum' that takes a function to map over. >>> asumMap (\x -> if x > 2 then Just x else Nothing) [1..4] Just 3@@ -83,18 +90,22 @@ asumMap = coerce (foldMap :: (a -> Alt m b) -> f a -> Alt m b) {-# INLINE asumMap #-} -{- | Polymorphic version of @concatMapA@ function.+{- | Polymorphic version of the 'concatMapA' function. >>> 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+ :: 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) {-# INLINE foldMapA #-} -{- | Polymorphic version of @concatMapM@ function.+{- | Polymorphic version of the 'Control.Monad.Extra.concatMapM' function. >>> foldMapM @[Int] (Just . replicate 3) [1..3] Just [1,1,1,2,2,2,3,3,3]
src/Relude/Foldable/Reexport.hs view
@@ -2,11 +2,12 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Foldable.Reexport+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Reexports "Data.Foldable" and "Data.Traversable". -}@@ -15,11 +16,9 @@ ( -- * @Foldable@ reexports module Data.Foldable , module Data.Traversable-#if MIN_VERSION_base(4,10,0) -- * @Bi@ reexports , module Data.Bifoldable , module Data.Bitraversable-#endif ) where import Data.Foldable (Foldable (fold, foldMap, foldl', foldr, length, null, toList), all, and, any,@@ -28,10 +27,8 @@ #if MIN_VERSION_base(4,13,0) import Data.Foldable (foldMap') #endif-import Data.Traversable (Traversable (..), forM, mapAccumL, mapAccumR)-#if MIN_VERSION_base(4,10,0) import Data.Bifoldable (Bifoldable (..), biList, biall, biand, biany, biasum, bielem, bifind, bifoldl', bifoldlM, bifoldr', bifoldrM, bifor_, bilength, binull, bior, bisequence_, bitraverse_) import Data.Bitraversable (Bitraversable (..), bifoldMapDefault, bifor, bimapDefault, bisequence)-#endif+import Data.Traversable (Traversable (..), forM, mapAccumL, mapAccumR)
src/Relude/Function.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Function+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable This module reexports very basic and primitive functions and function combinators.
src/Relude/Functor.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Functor+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Convenient functions to work with 'Functor'. -}
src/Relude/Functor/Fmap.hs view
@@ -2,13 +2,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Functor.Fmap+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable This module contains useful functions to work with 'Functor' type class. -}@@ -29,7 +30,12 @@ #else --- | Flipped version of '<$>'.+{- | Flipped version of '<$>'.++@+f <$> a = a <&> f+@+-} infixl 1 <&> (<&>) :: Functor f => f a -> (a -> b) -> f b as <&> f = f <$> as
src/Relude/Functor/Reexport.hs view
@@ -2,25 +2,29 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Functor.Reexport+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+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+ ( -- * Reexport Functor+ module Data.Functor , module Data.Functor.Compose , module Data.Functor.Identity #if MIN_VERSION_base(4,12,0) , module Data.Functor.Contravariant #endif++ -- * Reexport Bifunctor+ , module Data.Bifunctor ) where import Data.Bifunctor (Bifunctor (..))
src/Relude/Lifted.hs view
@@ -1,64 +1,65 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Lifted+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+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.+monad transformers without adding 'Relude.Monad.Reexport.liftIO' calls+explicitly. However, you still can use all these functions inside plain+ t'Relude.Base.IO' monad as usual. === Example ==== @base@ With the @base@ function, you can easily work with these functions in the-'Relude.IO' monad:+ t'Relude.Base.IO' monad: @-__main__ :: 'Relude.IO' ()+__main__ :: t'Relude.Base.IO' () __main__ = __do__ x <- 'Data.Text.getLine' 'Prelude.print' x @ -However, to work in 'Relude.MonadIO' you already need to "lift" them:+However, to work in t'Relude.Monad.Reexport.MonadIO' you already need to "lift" them: @-__main__ :: 'Relude.MonadIO' m => m ()+__main__ :: t'Relude.Monad.Reexport.MonadIO' m => m () __main__ = __do__- x <- 'Relude.liftIO' 'Data.Text.getLine'- 'Relude.liftIO' ('Prelude.print' x)+ x <- 'Relude.Monad.Reexport.liftIO' 'Data.Text.getLine'+ 'Relude.Monad.Reexport.liftIO' ('Prelude.print' x) @ ==== @relude@ -In the meantime, @relude@ provides these function that can work in 'Relude.IO'+In the meantime, @relude@ provides these function that can work in t'Relude.Base.IO' the same way: @-__main__ :: 'Relude.IO' ()+__main__ :: t'Relude.Base.IO' () __main__ = __do__ x <- 'getLine' 'print' x @ -But also allows you to work in the 'Relude.MonadIO' monads more easily:+But also allows you to work in the t'Relude.Monad.Reexport.MonadIO' monads more easily: @-__main__ :: 'Relude.MonadIO' m => m ()+__main__ :: t'Relude.Monad.Reexport.MonadIO' m => m () __main__ = __do__ x <- 'getLine' 'print' x @- -} module Relude.Lifted@@ -72,6 +73,10 @@ -- $file , module Relude.Lifted.Terminal -- $terminal+ , module Relude.Lifted.Handle+ -- $handle+ , module Relude.Lifted.Env+ -- $env ) where import Relude.Lifted.Concurrent@@ -79,6 +84,8 @@ import Relude.Lifted.File import Relude.Lifted.IORef import Relude.Lifted.Terminal+import Relude.Lifted.Handle+import Relude.Lifted.Env {- $concurrent Lifted 'MVar' and 'STM' functions.@@ -87,11 +94,17 @@ Lifted versions of functions that work with exit processes. -} {- $file-Lifted versions of functions working with files and common 'Relude.IO'.+Lifted versions of functions working with files and common t'Relude.Base.IO'. -} {- $ioref Lifted reexports from "Data.IORef" module. -} {- $terminal Lifted functions to work with stdin and stdout.+-}+{- $handle+Lifted functions to work with t'Relude.Base.IO' 'Handle's.+-}+{- $env+Lifted functions to work with system environment. -}
src/Relude/Lifted/Concurrent.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Lifted.Concurrent+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Lifted 'MVar' and 'STM' functions. -}
+ src/Relude/Lifted/Env.hs view
@@ -0,0 +1,44 @@+{-# LANGUAGE Safe #-}++{- |+Module : Relude.Lifted.Env+Copyright : (c) 2020-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable++Lifted functions to work with system environment.++@since 1.0.0.0+-}++module Relude.Lifted.Env+ ( getArgs+ , lookupEnv+ ) where++import Relude.Base (IO)+import Relude.Function ((.))+import Relude.Monad.Reexport (MonadIO (..), Maybe)+import Relude.String.Reexport (String)++import qualified System.Environment as ENV (getArgs, lookupEnv)++{- | Lifted version of 'System.Environment.getArgs'.++@since 1.0.0.0+-}+getArgs :: MonadIO m => m [String]+getArgs = liftIO ENV.getArgs+{-# SPECIALIZE getArgs :: IO [String] #-}+{-# INLINE getArgs #-}++{- | Lifted version of 'System.Environment.lookupEnv'.++@since 1.0.0.0+-}+lookupEnv :: MonadIO m => String -> m (Maybe String)+lookupEnv = liftIO . ENV.lookupEnv+{-# SPECIALIZE lookupEnv :: String -> IO (Maybe String) #-}+{-# INLINE lookupEnv #-}
src/Relude/Lifted/Exit.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Lifted.Exit+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Lifted versions of functions that work with exit processes. -}
src/Relude/Lifted/File.hs view
@@ -1,19 +1,24 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Lifted.File+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+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+#if ( __GLASGOW_HASKELL__ >= 900 )+ , readFile'+#endif , writeFile , appendFile ) where@@ -31,6 +36,19 @@ readFile = liftIO . IO.readFile {-# SPECIALIZE readFile :: FilePath -> IO String #-} {-# INLINE readFile #-}+{-# WARNING readFile ["'readFile' depends on the system's locale settings and can throw unexpected exceptions.", "Use 'readFileBS' or 'readFileLBS' instead."] #-}++#if ( __GLASGOW_HASKELL__ >= 900 )+{- | Lifted version of 'IO.readFile''. Strict version of 'readFile'.++@since 1.0.0.0+-}+readFile' :: MonadIO m => FilePath -> m String+readFile' = liftIO . IO.readFile'+{-# SPECIALIZE readFile' :: FilePath -> IO String #-}+{-# INLINE readFile' #-}+{-# WARNING readFile' ["readFile' depends on the system's locale settings and can throw unexpected exceptions.", "Use 'readFileBS' or 'readFileLBS' instead."] #-}+#endif -- | Lifted version of 'IO.writeFile'. writeFile :: MonadIO m => FilePath -> String -> m ()
+ src/Relude/Lifted/Handle.hs view
@@ -0,0 +1,70 @@+{-# LANGUAGE Safe #-}++{- |+Module : Relude.Lifted.Handle+Copyright : (c) 2020-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable++Lifted functions to work with 'IO' 'Handle's.++@since 1.0.0.0+-}++module Relude.Lifted.Handle+ ( hFlush+ , hIsEOF+ , hSetBuffering+ , hGetBuffering+ , Handle+ , stdin+ , stdout+ , stderr+ , withFile+ , BufferMode (..)+ ) where++import Relude.Base (IO)+import Relude.Function ((.))+import Relude.Bool (Bool (..))+import Relude.Monad.Reexport (MonadIO (..))+import qualified System.IO as IO (Handle, hFlush, hIsEOF, hSetBuffering, hGetBuffering, BufferMode)+import System.IO (Handle, stdin, stdout, stderr, withFile, BufferMode (..))++{- | Lifted version of 'IO.hFlush'.++@since 1.0.0.0+-}+hFlush :: MonadIO m => IO.Handle -> m ()+hFlush = liftIO . IO.hFlush+{-# SPECIALIZE hFlush :: IO.Handle -> IO () #-}+{-# INLINE hFlush #-}++{- | Lifted version of 'IO.hIsEOF'.++@since 1.0.0.0+-}+hIsEOF :: MonadIO m => IO.Handle -> m Bool+hIsEOF = liftIO . IO.hIsEOF+{-# SPECIALIZE hIsEOF :: IO.Handle -> IO Bool #-}+{-# INLINE hIsEOF #-}++{- | Lifted version of 'IO.hSetBuffering'.++@since 1.0.0.0+-}+hSetBuffering :: MonadIO m => IO.Handle -> IO.BufferMode -> m ()+hSetBuffering h = liftIO . IO.hSetBuffering h+{-# SPECIALIZE hSetBuffering :: IO.Handle -> IO.BufferMode -> IO () #-}+{-# INLINE hSetBuffering #-}++{- | Lifted version of 'IO.hGetBuffering'.++@since 1.0.0.0+-}+hGetBuffering :: MonadIO m => IO.Handle -> m IO.BufferMode+hGetBuffering = liftIO . IO.hGetBuffering+{-# SPECIALIZE hGetBuffering :: IO.Handle -> IO IO.BufferMode #-}+{-# INLINE hGetBuffering #-}
src/Relude/Lifted/IORef.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Lifted.IORef+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Lifted reexports from "Data.IORef" module. -}
src/Relude/Lifted/Terminal.hs view
@@ -1,11 +1,12 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Lifted.Terminal+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Lifted functions to work with stdin and stdout.
src/Relude/List.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.List+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Utility functions to work with lists and 'NonEmpty' lists. -}@@ -18,14 +19,17 @@ , module Relude.List.NonEmpty -- $nonempty , (!!?)+ , maybeAt+ , partitionWith ) where import Relude.Base ((<)) import Relude.Bool (otherwise)+import Relude.Function (flip, (.)) import Relude.List.NonEmpty import Relude.List.Reexport-import Relude.Monad (Maybe (..))+import Relude.Monad (Either, Maybe (..), partitionEithers) import Relude.Numeric (Int, (-)) @@ -33,8 +37,9 @@ -- >>> import Relude {- | Safer version of 'Relude.Unsafe.!!', returns a Maybe.-get element from list using index value starting from `0`. +Get element from list using index value starting from `0`.+ >>> [] !!? 0 Nothing @@ -60,6 +65,49 @@ go j (_:ys) = go (j - 1) ys go _ [] = Nothing {-# INLINE (!!?) #-}++{- | '!!?' with its arguments flipped.++Get element from list using index value starting from `0`.++>>> maybeAt 0 []+Nothing++>>> maybeAt 3 ["a", "b", "c"]+Nothing++>>> maybeAt (-1) [1, 2, 3]+Nothing++>>> maybeAt 2 ["a", "b", "c"]+Just "c"++@since 1.0.0.0+-}+maybeAt :: Int -> [a] -> Maybe a+maybeAt = flip (!!?)+{-# INLINE maybeAt #-}++{- | Partitions a list based on the result of function which produces an Either+value. List of all elements producing Left are extracted, in order, to the first+element of the output tuple. Similarly, a list of all elements producing Right+are extracted to the second element of output.++>>> :{+ divideEvenOrShow :: Int -> Either Int String+ divideEvenOrShow n+ | even n = Left $ n `div` 2+ | otherwise = Right $ "Odd: " <> show n+ :}++>>> partitionWith divideEvenOrShow [1 .. 6]+([1,2,3],["Odd: 1","Odd: 3","Odd: 5"])++@since 1.0.0.0+-}+partitionWith :: (a -> Either b c) -> [a] -> ([b], [c])+partitionWith f = partitionEithers . map f+{-# INLINE partitionWith #-} {- $reexport Most of the "Data.List" types and function.
src/Relude/List/NonEmpty.hs view
@@ -1,3 +1,9 @@+{-# LANGUAGE CPP #-}++#if __GLASGOW_HASKELL__ >= 902+{-# OPTIONS_GHC -Wno-operator-whitespace #-}+#endif+ {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE Safe #-}@@ -6,13 +12,14 @@ {-# LANGUAGE UndecidableInstances #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.List.NonEmpty+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable This module contains reexports from "Data.List.NonEmpty" and safe functions to work with list type in terms of 'NonEmpty'.@@ -87,6 +94,9 @@ ) where import Data.List.NonEmpty (NonEmpty (..), nonEmpty)+#if __GLASGOW_HASKELL__ >= 904+import Data.Type.Equality (type (~))+#endif import GHC.TypeLits (ErrorMessage (..), Symbol, TypeError) import Relude.Applicative (Applicative, pass)
src/Relude/List/Reexport.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Trustworthy #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.List.Reexport+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Reexports most of the "Data.List". -}@@ -22,7 +23,7 @@ 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,+ scanr, scanr1, sort, sortBy, sortOn, span, splitAt, subsequences, tails, take, takeWhile, transpose, uncons, unfoldr, unzip, unzip3, zip, zip3, zipWith, (++)) import GHC.Exts (sortWith)
src/Relude/Monad.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Monad+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Reexporting useful monadic stuff. -}@@ -22,12 +23,15 @@ , module Relude.Monad.Trans -- $trans , chainedTo+ , infinitely ) where import Relude.Monad.Either import Relude.Monad.Maybe import Relude.Monad.Reexport import Relude.Monad.Trans+import Control.Applicative (Applicative)+import Relude.Base (Void) -- $setup@@ -47,14 +51,39 @@ chainedTo = (=<<) {-# INLINE chainedTo #-} +{- | Repeat a monadic action indefinitely.++This is a more type safe version of 'forever', which has a convenient+but unsafe type.++Consider the following two examples. In the @getIntForever@ functions, it+falsely expects 'Int' as the result of the 'forever' function. But it would need+to wait *forever* to get that, and this mistake won't be caught by the type+system and compiler:++@+getIntForever :: IO Int+getIntForever = do+ i <- forever $ do ...+ pure i+@++In contrast, using 'infinitely' instead of 'forever' in 'foo' is a type error.++@since 1.0.0.0+-}+infinitely :: Applicative f => f a -> f Void+infinitely = forever+{-# INLINE infinitely #-}+ {- $reexport Reexports functions to work with different monads. -} {- $maybe-Provided new combinators to work with 'Relude.Maybe' data type.+Provided new combinators to work with 'Relude.Monad.Reexport.Maybe' data type. -} {- $either-Provided new combinators to work with 'Relude.Either' data type.+Provided new combinators to work with 'Relude.Monad.Reexport.Either' data type. -} {- $trans Monad transformers functions and combinators.
src/Relude/Monad/Either.hs view
@@ -1,18 +1,18 @@ {-# OPTIONS_GHC -fno-warn-orphans #-} -{-# LANGUAGE CPP #-} {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Monad.Either+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable -Utilities to work with 'Relude.Either' data type.+Utilities to work with 'Relude.Monad.Reexport.Either' data type. -} module Relude.Monad.Either@@ -37,6 +37,7 @@ import Control.Applicative (Applicative) import Control.Monad (Monad (..))+import Data.Either (fromLeft, fromRight) import Data.Function (const) import Data.Maybe (Maybe (..), maybe) @@ -44,32 +45,6 @@ import Relude.Function ((.)) import Relude.Monad.Reexport (Either (..), MonadFail (..), either) import Relude.String.Reexport (IsString (..), String)--#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)--- 3--- >>> fromLeft 0 (Right 5)--- 0-fromLeft :: a -> Either a b -> a-fromLeft _ (Left a) = a-fromLeft a (Right _) = a---- | Extracts value from 'Right' or return given default value.------ >>> fromRight 0 (Left 3)--- 0--- >>> fromRight 0 (Right 5)--- 5-fromRight :: b -> Either a b -> b-fromRight b (Left _) = b-fromRight _ (Right b) = b-#endif -- $setup
src/Relude/Monad/Maybe.hs view
@@ -1,15 +1,16 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Monad.Maybe+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable -Utility functions to work with 'Relude.Maybe' data type as monad.+Utility functions to work with 'Relude.Monad.Reexport.Maybe' data type as monad. -} module Relude.Monad.Maybe@@ -48,7 +49,7 @@ mA ?: b = fromMaybe b mA {-# INLINE (?:) #-} -{- | Specialized version of 'Relude.for_' for 'Maybe'. It's used for code readability.+{- | Specialized version of 'Relude.Foldable.Reexport.for_' for 'Maybe'. It's used for code readability. Also helps to avoid space leaks: <http://www.snoyman.com/blog/2017/01/foldable-mapm-maybe-and-recursive-functions Foldable.mapM_ space leak>.@@ -97,7 +98,7 @@ whenNothing_ _ _ = pass {-# INLINE whenNothing_ #-} -{- | Monadic version of 'whenNothingM'.+{- | Monadic version of 'whenNothing'. >>> whenNothingM (pure $ Just True) $ True <$ putTextLn "Is Just!" True@@ -109,7 +110,7 @@ whenNothingM mm action = mm >>= \m -> whenNothing m action {-# INLINE whenNothingM #-} -{- | Monadic version of 'whenNothingM_'.+{- | Monadic version of 'whenNothing_'. >>> whenNothingM_ (pure $ Just True) $ putTextLn "Is Just!" >>> whenNothingM_ (pure Nothing) $ putTextLn "Is Nothing!"
src/Relude/Monad/Reexport.hs view
@@ -1,25 +1,29 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Monad.Reexport+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+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+ ( -- * Reexport MonadIO+ MonadIO (liftIO)++ -- * 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+ , module Control.Monad.Trans.Maybe -- * Reexport monadic functions , module Control.Monad@@ -33,13 +37,14 @@ ) where -- Monad transformers+import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Except (ExceptT (..), runExceptT) import Control.Monad.Reader (MonadReader, Reader, ReaderT (..), ask, asks, local, reader, runReader, withReader, withReaderT) import Control.Monad.State.Strict (MonadState, State, StateT (..), evalState, evalStateT, execState, execStateT, get, gets, modify, modify', put, runState, state, withState)-import Control.Monad.Trans (MonadIO, MonadTrans, lift, liftIO)+import Control.Monad.Trans (MonadTrans, lift) import Control.Monad.Trans.Identity (IdentityT (runIdentityT)) import Control.Monad.Trans.Maybe (MaybeT (..), exceptToMaybeT, maybeToExceptT)
src/Relude/Monad/Trans.hs view
@@ -1,14 +1,14 @@-{-# LANGUAGE CPP #-} {-# LANGUAGE Trustworthy #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Monad.Trans+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Monad transformers utilities. -}@@ -17,10 +17,7 @@ ( -- * Convenient functions to work with 'Reader' monad usingReader , usingReaderT--#if MIN_VERSION_base(4,10,0) , etaReaderT-#endif -- * Convenient functions to work with 'State' monad , evaluatingState@@ -35,9 +32,7 @@ , 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)@@ -68,7 +63,6 @@ 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@@ -92,14 +86,13 @@ 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)>+* <https://www.joachim-breitner.de/blog/763-Faster_Winter_5__Eta-Expanding_ReaderT Faster Winter 5: Eta-Expanding ReaderT (by Joachim Breitner)> @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@.
src/Relude/Monoid.hs view
@@ -5,20 +5,21 @@ {-# LANGUAGE Trustworthy #-} #else {-# LANGUAGE Safe #-}-#endif {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Monoid+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Reexports functions to work with monoids plus adds extra useful functions. -} +#endif module Relude.Monoid ( -- * Reexports module Data.Monoid@@ -37,8 +38,8 @@ #endif import Data.Monoid (All (..), Alt (..), Any (..), Dual (..), Endo (..), First (..), Last (..), Monoid (..), Product (..), Sum (..))-import Data.Semigroup (Option (..), Semigroup (sconcat, stimes, (<>)), WrappedMonoid, cycle1,- mtimesDefault, stimesIdempotent, stimesIdempotentMonoid, stimesMonoid)+import Data.Semigroup (Semigroup (sconcat, stimes, (<>)), WrappedMonoid, cycle1, mtimesDefault,+ stimesIdempotent, stimesIdempotentMonoid, stimesMonoid) import Relude.Bool.Reexport (Bool (..)) import Relude.Monad.Reexport (Maybe, fromMaybe)@@ -47,7 +48,8 @@ import GHC.Generics (Generic1) import Relude.Applicative (Alternative, Applicative (..), liftA2)-import Relude.Base (Bounded (..), Enum, Eq, Generic, Ord, Show)+import Relude.Base (Eq, Generic, Ord, Show)+import Relude.Enum (Bounded (..), Enum) import Relude.Function (($), (.)) import Relude.Functor.Reexport (Functor (..)) import Relude.Monad.Reexport (Monad, MonadFail, MonadPlus)@@ -60,7 +62,7 @@ -- >>> import Relude.Monad (Maybe (..)) -- >>> import Relude.Numeric (Int) -{- | Extracts 'Monoid' value from 'Maybe' returning 'mempty' if 'Relude.Nothing'.+{- | Extracts 'Monoid' value from 'Maybe' returning 'mempty' if 'Relude.Monad.Reexport.Nothing'. >>> maybeToMonoid (Just [1,2,3] :: Maybe [Int]) [1,2,3]
src/Relude/Nub.hs view
@@ -1,13 +1,15 @@+{-# LANGUAGE CPP #-} {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Nub+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Functions to remove duplicates from a list. @@ -27,6 +29,10 @@ * 'hashNub' is the fastest with 'Data.Text.Text'. + * 'intNub' is faster when you work with lists of 'Int's.++ * 'intNubOn' is fast with the lists of type that can have fixed number representations.+ * 'sortNub' has better performance than 'ordNub' but should be used when sorting is also needed. * 'unstableNub' has better performance than 'hashNub' but doesn't save the original order.@@ -35,26 +41,48 @@ module Relude.Nub ( hashNub , ordNub++#if MIN_VERSION_containers(0,6,0)+ , ordNubOn+ , intNub+ , intNubOn+#endif+ , sortNub , unstableNub ) where +#if !MIN_VERSION_hashable(1,4,0) import Data.Eq (Eq)+#endif import Data.Hashable (Hashable) import Data.HashSet as HashSet import Data.Ord (Ord)-import Prelude ((.))+import Prelude (Int, (.)) import qualified Data.Set as Set+#if MIN_VERSION_containers(0,6,0)+import qualified Data.Containers.ListUtils as Containers+#endif -{- | Like 'Prelude.nub' but runs in \( O(n \log n) \) time and requires 'Ord'.+-- $setup+-- >>> import Prelude (div, fromEnum) +{- | Removes duplicate elements from a list, keeping only the first occurrence of+the element.++Like 'Prelude.nub' but runs in \( O(n \log n) \) time and requires 'Ord'.+ >>> ordNub [3, 3, 3, 2, 2, -1, 1] [3,2,-1,1] -} ordNub :: forall a . (Ord a) => [a] -> [a]+#if MIN_VERSION_containers(0,6,0)+ordNub = Containers.nubOrd+{-# INLINE ordNub #-}+#else ordNub = go Set.empty where go :: Set.Set a -> [a] -> [a]@@ -64,14 +92,34 @@ then go s xs else x : go (Set.insert x s) xs {-# INLINEABLE ordNub #-}+#endif ++#if MIN_VERSION_containers(0,6,0)+{- | Similar to 'ordNub' but performs nub through the mapped list on the given+function.++>>> ordNubOn (`div` 10) [3, 3, 3, 13, 2, 22, -1, 1, 66]+[3,13,22,-1,66]++@since 1.0.0.0+-}+ordNubOn :: forall b a . (Ord b) => (a -> b) -> [a] -> [a]+ordNubOn = Containers.nubOrdOn+{-# INLINE ordNubOn #-}+#endif+ {- | Like 'Prelude.nub' but runs in \( O(n \log_{16} n) \) time and requires 'Hashable'. >>> hashNub [3, 3, 3, 2, 2, -1, 1] [3,2,-1,1] -}+#if MIN_VERSION_hashable(1,4,0)+hashNub :: forall a . (Hashable a) => [a] -> [a]+#else hashNub :: forall a . (Eq a, Hashable a) => [a] -> [a]+#endif hashNub = go HashSet.empty where go :: HashSet.HashSet a -> [a] -> [a]@@ -98,6 +146,40 @@ [1,2,3,-1] -}+#if MIN_VERSION_hashable(1,4,0)+unstableNub :: (Hashable a) => [a] -> [a]+#else unstableNub :: (Eq a, Hashable a) => [a] -> [a]+#endif unstableNub = HashSet.toList . HashSet.fromList {-# INLINE unstableNub #-}+++#if MIN_VERSION_containers(0,6,0)+{- | Removes duplicate elements from a list, keeping only the first occurance of+the element.++Like 'Prelude.nub' but runs in \( O (n \min (n, int\_bits )) \) time and requires 'Ord'.++>>> intNub [3, 3, 3, 2, 2, -1, 1]+[3,2,-1,1]++@since 1.0.0.0+-}+intNub :: [Int] -> [Int]+intNub = Containers.nubInt++{-# INLINE intNub #-}++{- | Similar to 'intNub' but works on lists of any types by performing "nubbing" through 'Int's.++>>> intNubOn fromEnum "ababbbcdaffee"+"abcdfe"++@since 1.0.0.0+-}+intNubOn :: (a -> Int) -> [a] -> [a]+intNubOn = Containers.nubIntOn+{-# INLINE intNubOn #-}++#endif
src/Relude/Numeric.hs view
@@ -1,11 +1,12 @@ {-# LANGUAGE Trustworthy #-} {- |-Copyright: (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Numeric+Copyright : (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Provides numerical data types and functions. @@ -38,8 +39,9 @@ denominator, even, fromIntegral, gcd, lcm, numerator, odd, realToFrac, (^), (^^)) import Numeric.Natural (Natural) -import Relude.Base (Bounded (..), (<), (>))+import Relude.Base ((<), (>)) import Relude.Bool (otherwise)+import Relude.Enum (Bounded (..)) import Relude.Function (($)) import Relude.Monad (Maybe (..)) @@ -55,6 +57,19 @@ >>> integerToBounded @Int8 1024 Nothing++>>> integerToBounded @Int (toInteger (minBound :: Int))+Just (-9223372036854775808)+>>> integerToBounded @Int $ (toInteger (minBound :: Int)) - 1+Nothing++>>> integerToBounded @Int (toInteger (maxBound :: Int))+Just 9223372036854775807+>>> integerToBounded @Int $ (toInteger (maxBound :: Int)) + 1+Nothing++If you want to convert 'Int' or 'Word' to a bounded type, take a look at+'toIntegralSized' function instead. @since 0.5.0 -}
src/Relude/Print.hs view
@@ -4,13 +4,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Print+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Functions like 'Prelude.putStr' and 'Prelude.putStrLn' but for 'Text', 'LText', 'ByteString' and 'LByteString'.
src/Relude/String.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Safe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.String+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Type classes for conversion between different string representations. @@ -36,7 +37,6 @@ +-----------------------+---------------------+--------------+--------------+--------------------+------------------------+--------------------------+ | __'ShortByteString'__ | 'decodeUtf8' | 'decodeUtf8' | 'fromShort' | 'decodeUtf8' |@'toLazy' . 'fromShort'@| ~ | +-----------------------+---------------------+--------------+--------------+--------------------+------------------------+--------------------------+- -} module Relude.String
src/Relude/String/Conversion.hs view
@@ -1,4 +1,9 @@ {-# LANGUAGE CPP #-}++#if __GLASGOW_HASKELL__ >= 902+{-# OPTIONS_GHC -Wno-operator-whitespace #-}+#endif+ {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-}@@ -10,13 +15,14 @@ {-# LANGUAGE UndecidableInstances #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.String.Conversion+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+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@@ -100,8 +106,17 @@ >>> decodeUtf8 @Text @ByteString "\208\208\176\209\130\208\176\208\186" "\65533\65533\1090\1072\1082" #endif++#if MIN_VERSION_text(2,0,2) >>> decodeUtf8Strict @Text @ByteString "\208\208\176\209\130\208\176\208\186"- Left Cannot decode byte '\xd0': Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream+ Left Cannot decode byte '\xd0': ...: Invalid UTF-8 stream+#elif MIN_VERSION_text(2,0,0)+ >>> decodeUtf8Strict @Text @ByteString "\208\208\176\209\130\208\176\208\186"+ Left Cannot decode byte '\xd0': ...: Invalid UTF-8 stream+#else+ >>> decodeUtf8Strict @Text @ByteString "\208\208\176\209\130\208\176\208\186"+ Left Cannot decode byte '\xd0': ...: Invalid UTF-8 stream+#endif -} decodeUtf8Strict :: b -> Either T.UnicodeException a
src/Relude/String/Reexport.hs view
@@ -1,3 +1,9 @@+{-# LANGUAGE CPP #-}++#if __GLASGOW_HASKELL__ >= 902+{-# OPTIONS_GHC -Wno-operator-whitespace #-}+#endif+ {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-}@@ -7,13 +13,14 @@ {-# LANGUAGE UndecidableInstances #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.String.Reexport+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable Reexports functions to work with 'Data.Text.Text', 'ByteString' and 'ShortByteString' types.@@ -49,6 +56,9 @@ import Data.Text.Encoding (decodeUtf8', decodeUtf8With) import Data.Text.Encoding.Error (OnDecodeError, OnError, UnicodeException, lenientDecode, strictDecode)+#if __GLASGOW_HASKELL__ >= 904+import Data.Type.Equality (type (~))+#endif import GHC.TypeLits (ErrorMessage (..), Symbol, TypeError) import Text.Read (Read, readMaybe, reads)
src/Relude/Unsafe.hs view
@@ -1,13 +1,14 @@ {-# LANGUAGE Unsafe #-} {- |-Copyright: (c) 2016 Stephen Diehl- (c) 2016-2018 Serokell- (c) 2018-2020 Kowainik-SPDX-License-Identifier: MIT-Maintainer: Kowainik <xrom.xkov@gmail.com>-Stability: Stable-Portability: Portable+Module : Relude.Unsafe+Copyright : (c) 2016 Stephen Diehl+ (c) 2016-2018 Serokell+ (c) 2018-2023 Kowainik+SPDX-License-Identifier : MIT+Maintainer : Kowainik <xrom.xkov@gmail.com>+Stability : Stable+Portability : Portable __⚠️ Warning ⚠️__ @@ -17,9 +18,9 @@ +-----------------------------------+---------------------------------------------------------------------+ | __Partial__ | __Total__ | +===================================+=====================================================================+-| @'head' :: [a] -> a@ | @'Relude.head' :: NonEmpty a -> a@ |+| @'head' :: [a] -> a@ | @'Relude.List.NonEmpty.head' :: NonEmpty a -> a@ | +-----------------------------------+---------------------------------------------------------------------+-| @'tail' :: [a] -> [a]@ | @'Relude.tail' :: NonEmpty a -> [a]@ |+| @'tail' :: [a] -> [a]@ | @'Relude.List.NonEmpty.tail' :: NonEmpty a -> [a]@ | +-----------------------------------+---------------------------------------------------------------------+ | @'read' :: Read a => String -> a@ | @'Relude.String.Reexport.readMaybe' :: Read a => String -> Maybe a@ | +-----------------------------------+---------------------------------------------------------------------+
test/Doctest.hs view
@@ -9,7 +9,8 @@ main = do sourceFiles <- glob "src/**/*.hs" doctest- $ "-XInstanceSigs"+ $ "-XHaskell2010"+ : "-XInstanceSigs" : "-XNoImplicitPrelude" : "-XOverloadedStrings" : "-XScopedTypeVariables"
− test/Test/Relude/Extra/Validation/Property.hs
@@ -1,168 +0,0 @@-{- HLINT ignore "Alternative law, right identity" -}-{- HLINT ignore "Alternative law, left identity" -}-{- HLINT ignore "Monoid law, right identity" -}-{- HLINT ignore "Monoid law, left identity" -}-{- HLINT ignore "Use <$>" -}--module Test.Relude.Extra.Validation.Property- ( validationLaws- ) where--import Relude-import Relude.Extra.Validation--import Hedgehog (Gen, Group (..), Property, forAll, forAllWith, property, (===))--import qualified Hedgehog.Gen as Gen-import qualified Hedgehog.Range as Range--validationLaws :: [Group]-validationLaws =- [ validationSemigroupProps- , validationMonoidProps- , validationApplicativeProps- , validationAlternativeProps- ]--------------------------------------------------------------------------------- Generators-------------------------------------------------------------------------------genFunction :: Gen (Int -> Int)-genFunction = Gen.element [(+), (*), const] <*> genSmallInt--genSmallInt :: Gen Int-genSmallInt = Gen.int (Range.linear (-10) 10)--genSmallText :: Gen Text-genSmallText = Gen.text (Range.linear 3 10) Gen.unicode--asValidation :: Gen a -> Gen (Validation [Text] a)-asValidation gen = Gen.choice- [ Success <$> gen- , Failure <$> Gen.list (Range.linear 1 5) genSmallText- ]--------------------------------------------------------------------------------- Property helpers-------------------------------------------------------------------------------checkAssociativityFor- :: (Show a, Eq a) => Gen a -> (a -> a -> a) -> Property-checkAssociativityFor gen op = property $ do- a <- forAll gen- b <- forAll gen- c <- forAll gen- a `op` (b `op` c) === (a `op` b) `op` c--------------------------------------------------------------------------------- Semigroup instance properties-------------------------------------------------------------------------------validationSemigroupProps :: Group-validationSemigroupProps =- Group "Semigroup instance for Validation property tests"- [ ("associativity:", prop_semigroupAssociativity)- ]--prop_semigroupAssociativity :: Property-prop_semigroupAssociativity =- checkAssociativityFor (asValidation genSmallText) (<>)--------------------------------------------------------------------------------- Monoid instance properties-------------------------------------------------------------------------------validationMonoidProps :: Group-validationMonoidProps =- Group "Monoid instance for Validation property tests"- [ ("right identity:", prop_monoidRightIdentity)- , ("left identity:", prop_monoidLeftIdentity)- ]--prop_monoidRightIdentity :: Property-prop_monoidRightIdentity = property $ do- x <- forAll $ asValidation genSmallText- x <> mempty === x--prop_monoidLeftIdentity :: Property-prop_monoidLeftIdentity = property $ do- x <- forAll $ asValidation genSmallText- mempty <> x === x--------------------------------------------------------------------------------- Applicative instance properties-------------------------------------------------------------------------------validationApplicativeProps :: Group-validationApplicativeProps =- Group "Applicative instance for Validation property tests"- [ ("identity:", prop_applicativeIdentity)- , ("composition:", prop_applicativeComposition)- , ("homomorphism:", prop_applicativeHomomorphism)- , ("interchange:", prop_applicativeInterchange)- , ("u *> v == (id <$ u) <*> v", prop_applicativeApplyRight)- , ("u <* v == liftA2 const u v", prop_applicativeApplyLeft)- ]--prop_applicativeIdentity :: Property-prop_applicativeIdentity = property $ do- vx <- forAll $ asValidation genSmallText- (pure id <*> vx) === vx--prop_applicativeComposition :: Property-prop_applicativeComposition = property $ do- vf <- forAllWith (const "f") $ asValidation genFunction- vg <- forAllWith (const "g") $ asValidation genFunction- vx <- forAll $ asValidation genSmallInt- (pure (.) <*> vf <*> vg <*> vx) === (vf <*> (vg <*> vx))--prop_applicativeHomomorphism :: Property-prop_applicativeHomomorphism = property $ do- f <- forAllWith (const "f") genFunction- x <- forAll genSmallInt- (pure f <*> pure x) === pure @(Validation [Text]) (f x)--prop_applicativeInterchange :: Property-prop_applicativeInterchange = property $ do- vf <- forAllWith (const "f") $ asValidation genFunction- x <- forAll genSmallInt- (vf <*> pure x) === (pure ($ x) <*> vf)--prop_applicativeApplyRight :: Property-prop_applicativeApplyRight = property $ do- vy <- forAll $ asValidation genSmallInt- vx <- forAll $ asValidation genSmallInt- (vy *> vx) === ((id <$ vy) <*> vx)--prop_applicativeApplyLeft :: Property-prop_applicativeApplyLeft = property $ do- vy <- forAll $ asValidation genSmallInt- vx <- forAll $ asValidation genSmallInt- (vy <* vx) === liftA2 const vy vx--------------------------------------------------------------------------------- Alternative instance properties-------------------------------------------------------------------------------validationAlternativeProps :: Group-validationAlternativeProps =- Group "Alternative instance for Validation property tests"- [ ("associativity:", prop_alternativeAssociativity)- , ("right identity:", prop_alternativeRightIdentity)- , ("left identity:", prop_alternativeLeftIdentity)- ]--prop_alternativeAssociativity :: Property-prop_alternativeAssociativity =- checkAssociativityFor (asValidation genSmallText) (<|>)--prop_alternativeRightIdentity :: Property-prop_alternativeRightIdentity = property $ do- x <- forAll $ asValidation genSmallText- (x <|> empty) === x--prop_alternativeLeftIdentity :: Property-prop_alternativeLeftIdentity = property $ do- x <- forAll $ asValidation genSmallText- (empty <|> x) === x
test/Test/Relude/Property.hs view
@@ -8,7 +8,6 @@ import Hedgehog (Group (..), Property, assert, forAll, property, (===)) import Test.Relude.Container.One (oneProps)-import Test.Relude.Extra.Validation.Property (validationLaws) import Test.Relude.Gen (genBoolList, genIntList, genUtf8ByteString, genUtf8String, genUtf8Text) @@ -18,7 +17,7 @@ , listProps , logicProps , oneProps- ] <> validationLaws+ ] ---------------------------------------------------------------------------- -- utf8 conversion