Questions tagged [monads]
A monad in programming is a composable computation description. Monads are an important construct in functional programming languages like Haskell.
3,339
questions
3
votes
2
answers
88
views
Monadic function of `(a -> m (Either e b)) -> Either e a -> m (Either e b)`?
Is there a way to write this function in a more "monadic" way, instead of resorting to pattern matching on Either?
{-# LANGUAGE LambdaCase #-}
calculate :: (Monad m) => (a -> m (...
0
votes
0
answers
20
views
Conventional way to save an aggregation over initial data to use in further processing in fp-ts
A common use case that I encounter is the need to pre-calculate some data set for further use in computation, i.e.
const users = [{active: false, id: 'userId1'}, {active: true, id: 'userId2}];
const ...
6
votes
1
answer
249
views
Why does ArrowKt reccomend I implement my effect interface with an object instead of a function?
According to the docs I should implement an effect with an object.
fun interface JustEffect<A> : Effect<Just<A>> {
suspend fun <B> Just<B>.bind(): B = value
}
object ...
1
vote
1
answer
98
views
Elegant way to access the value of a record in haskell which is inside a monad
Generalisation of question (read below for specifics to my current problem)
Given a function type definition: f :: MonadIO m -> a -> m B where B is a custom datatype B = B {x y z ...} how can I ...
6
votes
0
answers
93
views
Best way to combine multiple state/reader monads?
I am writing a project that involves composing several stacks of StateT and ReaderT monads:
newtype FooT m a = FooT { unFooT :: (StateT State1 (ReaderT Reader1 m)) a }
newtype BarT m a = BarT { ...
3
votes
2
answers
100
views
Haskell Monad task
So we have following Data Types:
data Expr = Num Double | Add Expr Expr | Var Char deriving Show
and
type Env = [(Char, Double)]
Further More we have these two functions:
evalDo :: Env -> Expr ->...
2
votes
0
answers
71
views
Interpreting the `Reader` trait in "Simplicitly"
In "Simplicitly: foundations and applications of implicit function types", Odersky et al. briefly introduce the Reader monad, just to replace it with a superior alternative one paragraph ...
3
votes
1
answer
132
views
How to execute deterministic code from an untrusted third party safely?
I understand that there are several questions similar to mine, however my problem is a little different and I haven't found a proper answer.
I know a simple way to run code from untrusted sources is ...
0
votes
1
answer
36
views
TypeScript generic type constraints can't deduct type
I am playing with TypeScript type system and I seem to have hit an invisible wall.
For starters, I have the Func helper type (since Function is not a generic type in TypeScript):
type Func <A, B>...
0
votes
1
answer
81
views
Haskell traverse and filter through a list while lifting results
Say I have code where I want to do the following:
Input: a list of strings [String]
Operation (checkSat and checkResult)
Obtains a boolean from an input string.
Output:
If everything in the input ...
3
votes
1
answer
170
views
Short-circuit list, type of `(a -> Either e a) -> [a] -> Either e [a]` ... monadic operation?
Consider the following function:
validateList :: (a -> Either e a) -> [a] -> Either e [a]
validateList validate [] = Right []
validateList validate (x:xs) =
case validate x of
...
0
votes
2
answers
173
views
All possible binary trees storing a value
I want to write a function, allTrees, to generate a list of all possible binary trees that store the number of leaves each tree has.
Here are my data types and my attempt at the allTrees function:
...
2
votes
0
answers
71
views
How to Group and Split Monad Transformers using Identity
I am currently learning about Monad Transformers and noticed that the MonadTrans class that the library I am using (Mageparsec) implements, does not define any way to group and split apart the ...
2
votes
1
answer
236
views
What is the advantage of Option/Maybe Monad over Functor?
I understand the advantage of IO monad and List Monad over Functor, however, I don't understand the advantage of Option/Maybe Monad over Functor.
Is that simply the integration of types of the ...
2
votes
0
answers
46
views
Are monads in functional programming, well, actually monads?
As an (applied) mathematician by training, I've been trying to get my head around monads and category theory applied to functional programming. I understand the power of monads, and notably ...
0
votes
1
answer
57
views
Witchcraft IO monad?
Background
I have recently been delving into more functional code. My objective right now is to get something similar to the IO Monad (in Haskell, Scala, etc) but in Elixir.
To this extent, I ...
10
votes
7
answers
237
views
Functional composition of Optionals
I have 2 Optionals (or Maybe objects) that I would like to combine so that I get the following results:
|| first operand
second ++-------------+-------------
...
4
votes
1
answer
133
views
Confusing ReaderT definition
As an exercise I've been reimplementing some common monads and their corresponding transformers; here are some of the types I've defined:
newtype Writer w a = Writer { runWriter :: (w, a) }
...
1
vote
1
answer
48
views
Retrieving Logging Messages From Wiki Monad Example Not Working
I am learning about monads. I read this Wiki page thoroughly and reached the Program logging section. I've decided to implement that in C#.
An example starts with two simple functions/methods, which ...
4
votes
2
answers
156
views
Is the monad transformer of a monad unique in Haskell?
There have been a couple of questions (e.g. this and this) asking whether every monad in Haskell (other than IO) has a corresponding monad transformer. Now I would like to ask a complementary question....
1
vote
1
answer
31
views
Scala: for-comprehension with recursive Future
The task is to realise recursive method, which returns Future
def recursive (result:List[Result], attempt: Int):Future[Seq[Result]] = attempt match {
case a if a < 3 => {
for {
...
1
vote
1
answer
38
views
How to bind a class that extends a trait with a monadic type in Scala Guice
I've created simple Scala Play application that has traits with a monadic type and their respective implementation binded in Module configure as:
class Module extends AbstractModule {
override ...
1
vote
1
answer
79
views
No instance for (MonadWriter [Log] IO) arising from a use of ‘tell’
Consider this toy exercise on Writer and WriterT: We need to filter a list of packets based on a predefined set of rules. We also need to log some packets based on another set of rules. Now consider ...
1
vote
0
answers
90
views
Immitating a global list in Haskell to generate a unique random value
I'm currently building a toy meal planning application and have decided to write the back-end in Haskell simply to challenge myself. The problem that I'm having is described in the title in which I ...
0
votes
1
answer
36
views
Rails 6 get error message from Failure monad results
Is it possible to get error message which was passed as a Failure monad result? as far as I can see the value! method is provided for Success but is it possible to get message from Failure as well?
...
0
votes
1
answer
44
views
Rails 6 monads pattern matching to fetch only success/failure
Is there any build in or some nifty way to fetch only Success or Failure results from array of monad results?
e.g.
state
=> [Failure("12345 Product code is not valid"), Success("...
2
votes
1
answer
91
views
In depth understanding of Monad
At one time, I thought I understood Monad. However, when I try to connect my understanding of code to the piece of theory, I found myself still not clear. So here it is:
part 1. Here is the popular ...
2
votes
2
answers
59
views
How to define a Monad for a function type?
I am trying Cats for the first time and am using Scala 3, and I am trying to implement a set of parser combinators for self-pedagogy, however; I am stuck on the definition of the tailRecM function for ...
2
votes
1
answer
109
views
When implementing bind, why name the second parameter k? [closed]
instance Monad M where
m >>= k = ...
Also is there a name for functions which are used as this second argument to bind?
5
votes
1
answer
153
views
Is there a way to commute monads automatically?
I have written a program to pull a Maybe out of a pair:
deMaybe :: (a, Maybe b) -> Maybe (a, b)
deMaybe (_, Nothing) = Nothing
deMaybe (x,Just y) = Just (x, y)
I know that Maybe is a monad and (,) ...
2
votes
1
answer
158
views
The identity monad as a free monad
The functor of the identity monad can be defined as:
data Identity a = Identity a
Because this monad is free, an alternative definition is the following:
data Term f a = Pure a | Impure (f (Term f a))...
2
votes
2
answers
130
views
How do define a monad transformer that is the composition of two arbitrary monad transformers?
I want to write something similar to the following:
newtype FooT c d m a = FooT { unFooT :: (c (d m)) a }
instance (MonadTrans c, MonadTrans d) => MonadTrans (FooT c d) where
lift = FooT . lift ....
1
vote
2
answers
136
views
Useful monads for multi-paradigm languages
I finally got my head around monads once I understood how they are useful in c++/python by allowing you to chain together functions of the form T -> Generic<U>. For example, if you have
...
0
votes
1
answer
108
views
Indexed monads for state machines
I decided to experiment with indexed monads to create a type-safe state machine. That means Haskell will refuse to compile illegal state transitions.
My questions are.
I created a Door type with ...
0
votes
1
answer
97
views
Haskell mapM_ does not print
So I wrote a program to query a forex API (foreign exchange), and it works like a charm, but when I want to query every currency pair available, it evaluates all API calls as it takes a long time to ...
2
votes
1
answer
95
views
Monadic bind with Cmd
I have a function
convertMsg : Msg1 -> List Msg2
where Msg1 and Msg2 are certain message types. And I would like to turn this into a function:
convertCmd : Cmd Msg1 -> Cmd Msg2
Which would ...
0
votes
1
answer
62
views
Scala concatenate Map - one with Option and other without Option
I have the below input values
import java.sql.Timestamp
import java.lang.{Double => JDouble}
val date = Timestamp.valueOf("2021-08-01 00:00:00")
val contractRate: Map[String, JDouble] = ...
1
vote
1
answer
188
views
A Reader monad for multiple arguments?
Is there an equivalent to the Reader monad that's equivalent to a -> b -> c rather than just a -> b. I know I could do (a, b) -> c but I'm not sure that's going to be very ergonomic.
2
votes
2
answers
240
views
What is the mathematical theory or theorem underlying join of monad?
For example:
Maybe (Maybe Bool) -> Maybe Bool
Just (Just True) -----> Just True
Just (Just False) ----> Just False
Just (Nothing) -------> Nothing
Nothing ------------...
1
vote
0
answers
39
views
How to handle multiple errors in Haskell IO context [duplicate]
I'm learning Haskell (from LYAH) and just starting to understand monads. I am trying to write a command line program which parses the command line, opens and reads a file (or files) whose paths are ...
0
votes
1
answer
128
views
Regardless of composition, can I say monadic if there is only a way to change m(m a) to m a
Monad has the following components.
a and m a which converted from a by a Functor
a -> m b arrow and a way to change m m to m
composition of arrows
If there is a structure that has 1,2 regardless ...
4
votes
1
answer
78
views
Haskell theorem proving tactics as indexed functors and monads
I am trying to follow along with this blog post to make a simple intuitionistic theorem proving language in Haskell. Mr. van Bakel suggests using indexed monads for proof state manipulation; here are ...
1
vote
1
answer
183
views
Migrating to Dart null safety: best practice for migrating ternary operator null checks? Is a monadic approach too unconventional?
I'm migrating a code base to null safety, and it includes lots of code like this:
MyType convert(OtherType value) {
return MyType(
field1: value.field1,
field2: value.field2 != null ? ...
10
votes
1
answer
266
views
Did this construction of free(freer?) monad works?
In the past 2 years, I was interested in using free monad to helping me to solve practical software engineering problem. And came up my own construction of free monad using some elementary category ...
3
votes
2
answers
87
views
iteration with the list monad
I'm having trouble understanding how the iterative behavior of the list monad can be derived from its definition.
instance Monad [] where
m >>= f = concatMap f m
return x = [x]
fail s = ...
0
votes
1
answer
134
views
Using monad for cumulative sum on list of pairs (haskell)
I have a list of pairs structure [("oct",1),("nov",1),("dec",1)]
I want to calculate sum within pairs: [("oct",1),("nov",2),("dec",3)]. I ...
2
votes
2
answers
185
views
Can I say that Monad makes it possible to see some types as isomorphic?
Monad can pass Just [1,2], which is a different type from what the original length function takes, to >>= return . length.
Just [1,2] >>= return . length
Can I say that Monad makes it ...
7
votes
1
answer
97
views
Haskell -- Understanding the writer type declaration
I am learning about monads in the book 'Learn You a Haskell for Great Good!' by Miran Lipovaca. I am reading about how the Control.Monad.Writer module exports the Writer w a type along with its Monad ...
4
votes
3
answers
135
views
How does Haskell "desugar" getline in this do block?
I've read a few books on Haskell but haven't coded in it all that much, and I'm a little confused as to what Haskell is doing in a certain case. Let's say I'm using getLine so the user can push a key ...
0
votes
1
answer
53
views
Right not working with for comprehension Scala
Background
I am trying to use comprehensions with Scala with the Either type, namely using a Right.
However, despite my efforts, I get an error and nothing works.
Code
I am using scala's repl to make ...