You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/docs/reference/contextual/typeclasses-new.md
+52-1Lines changed: 52 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -201,7 +201,58 @@ given optionMonad as Monad[Option] {
201
201
Another example of a `Monad` is the Reader Monad. It no longer acts on a type like `List` or `Option`, but on a function.
202
202
It can be used for example for combining functions that all need the same type of parameter. For instance multiple functions needing access to some configuration, context, environment variables, etc.
203
203
204
-
The Reader monad allows to abstract over such a configuration dependency (or context, environment, ...), named `Ctx` in the following examples. It is therefore _parameterized_ by `Ctx`:
204
+
Let us have a `Config` type, and two functions using it:
205
+
206
+
```scala
207
+
traitConfig
208
+
defcompute(i: Int)(config: Config):String=???
209
+
defshow(str: String)(config: Config):Unit=???
210
+
```
211
+
212
+
We may want to combine `compute` and `show` into a single function, accepting a `Config` as parameter, and showing the result of the computation.
213
+
If we had a `flatMap` function as in the examples above, we would be able to write the following:
Let's define this `Monad` then. First, we are going to define a type named `ConfigDependent` representing a function that when passed a `Config` produces a `Result`.
220
+
221
+
```scala
222
+
traitConfig// the Config defined above
223
+
typeConfigDependent[Result] =Config=>Result
224
+
```
225
+
226
+
The monad will look like this:
227
+
228
+
```scala
229
+
givenconfigDependentMonad as Monad[ConfigDependent]
0 commit comments