I´ve gotten into a bit of confusion whether Maybe Int and Maybe String are both monoids in Haskell because i dont really know what functions you can apply to Int or String in terms of monoids with their neutral element and associativity rules! Can anybody help me out?
Are Maybe String and Maybe Int both Monoids in Haskell?
244 views Asked by GDash 69 At
2
There are 2 answers
3
chepner
On
There is a Monoid instance for any Maybe a as long as a itself has a Monoid instance; the combination of two Just values simply combines the wrapped values according to their instance, while anything combined with Nothing is itself Nothing.
String has a Monoid instance by virtue of being an alias of [Char]; all lists are monoids via list concatenation with the empty list as the identity. As a result, Maybe String is a monoid as well.
> Just "Fo" <> Just "o"
Just "Foo"
> Just "Fo" <> Nothing
Just "Fo"
Maybe Int is not a monoid, because Int is not a monoid. This is because there are multiple choices for how to make Int a monoid, so no one choice is chosen as special. Instead, several new types are defined with distinct Monoid instances to clarify which operation you want to use.
> import Data.Monoid
> (3 :: Int) <> 5
<interactive>:8:1: error:
• No instance for (Semigroup Int) arising from a use of ‘<>’
• In the expression: (3 :: Int) <> 5
In an equation for ‘it’: it = (3 :: Int) <> 5
-- (+) and 0
> Sum (3 :: Int) <> Sum 5
Sum {getSum = 8}
-- (*) and 1
> Product (3 :: Int) <> Product 5
Product {getProduct = 15}
> Just (Sum (3 :: Int)) <> Just (Sum 5)
Just (Sum {getSum = 8})
> Just (Sum (3 :: Int)) <> Nothing
Just (Sum {getSum = 3})
Related Questions in STRING
- What does: "char *argv[]" mean?
- User input sanitization program, which takes a specific amount of arguments and passes the execution to a bash script
- JSON Body is Not Passing Certain Strings
- Regex to match repeated substring in Google Sheets
- Find the sum of the numbers in the sequence
- Hello, how can I use a block parameter of withstyle parameter when we create a annotated string in jetpackpack compose
- How to convert an HTML string to an escaped one?
- Quintic Number Number Counting Hash Function
- From Buffer("string", "hex) to string JS
- Calling ToString with a nominated format returns Char rather than String
- How to update an already existing array by accessing it by a variable with the exact same name assigned to it
- Why does \b not interpreted as backslash in this regular expression
- Python: why aren’t strings being internalized if they are received from ints by using str()?
- If the element(s) in the first list equal element(s) of the second list, replace with element(s) of the third list
- About Suffix Trees features
Related Questions in HASKELL
- Typeclass projections as inheritance
- How to generate all possible matrices given a number n in Haskell
- Is there a way to get `cabal` to detect changes to non-Haskell source files?
- How to have fixed options using Option.Applicative in haskell?
- How can I create a thread in Haskell that will restart if it gets killed due to any reason?
- Automatic Jacobian matrix in Haskell
- Haskell writing to named pipe unexpectedly fails with `openFile: does not exist (No such device or address)`
- Why does Enum require to implement toEnum and fromEnum, if that's not enough for types larger than Int?
- Non-exhaustive patterns in function compress
- How to get terms names of GADT in Template Haskell?
- Implementing eval() function with Happy parser generator
- How to count the occurences of every element in a list in Haskell fast?
- In Haskell, what does `Con Int` mean?
- Extract a Maybe from a heterogeneous collection
- Haskell, Stack, importing module shows error "Module not found"
Related Questions in INTEGER
- Python: why aren’t strings being internalized if they are received from ints by using str()?
- Covert a numbers list (pulled from excel) first into integer then string
- Pinescript Warning of only support to Simple Integer and asking to eliminate the Series Integer
- Get int value from Enum in Visual Scripting (Unity)
- Overcoming TypeError: can't multiply sequence by non-int of type 'list'
- int too large to convert to float, but even larger numbles can be handled
- Using an int from a for loop in another for loop. JAVA
- Alternatives to fractional types
- Is it possible to solve this sumDouble problem with an if else function?
- Checking if a string with leading zeros is a valid integer in Kotlin
- Why 00 is a valid integer in Python?
- How do I classify a float as an integer?
- Am having this error while trying to test my SMTP
- Comparing Multiple Integers in C Workaround
- R ggplot2: Is it possible to remove the zero label after using expand_limits(x = 0)?
Related Questions in OPTION-TYPE
- Springboot: How to get an entity optional property and check null?
- Typescript Maybe, error about null not being covered
- Optional.ifPresent throws NPE when action is null AND optional not present
- Monad Map with two values in Java Functional Programming
- Runtime Issues with std::optional in GCC on M2 Mac
- Chain an "if let" with a boolean expression
- Show CSS in Option of Dropdownlist
- How to get subslice of Options instead of Option of subslice?
- Swift, Why are the memory sizes of 'String' and 'String?' the same?
- Optional and complete method
- Pure functional way of creating a std::optional counterpart
- Equivalent of "Optional" (maybe type) from Java in Powershell
- Is using a wrapper with a 'check' function a good approach to optional types rather than the traditional method?
- What is the best way to check if the value inside an option inside a result satisfies a condition in rust?
- Getopt::Long, Optional Arguments, and Greediness
Related Questions in MONOIDS
- Does a Maybe Monad collapses in Just or Nothing?
- Turn endomorphisms into Applicative
- Is there a class that models "patches"?
- Haskell newtype that flips semigroup operation?
- Application of monoid to sum of list for special case when list is empty
- A monoid can see its elements all in the same shape
- Is there a semigroup/monoid in the context of a monad?
- Why is my Semigroup/Monoid instance overlapping?
- For what Alt in Monoid instance needed?
- How can I write the fsum foldable function in haskell?
- Are Maybe String and Maybe Int both Monoids in Haskell?
- Haskell, implementing Monoids. What is Semigroup and why does it act so weird?
- Are monads in functional programming, well, actually monads?
- Confused about why all morphisms for a monoid are not the same as the identity morphism
- What is a cocartesian comonoid, and what is a cocartesian comonoidal functor?
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Popular Tags
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
The
Monoidinstance forMaybetypes has been defined as [src]:it thus requires
IntorStringto be instances of theSemigrouptype class. Since aStringis the same astype String = [Char]and thus a list ofChars, this is the case, indeed we see [src]:so it will append the two lists, and for a
Maybethis means [src]:This thus means that for two
Maybe Strings, the neutral element isNothingand the binary operator will append the two strings wrapped inJust …data constructors if these are bothJusts, theJustone if one of the two is aJust, orNothingif both items areNothings.This is not the case for an
Int, indeed. For integers there can be multipleMonoidinstances, for example ⟨ℤ,+, 0⟩ or ⟨ℤ,×, 1⟩.