Why the difference in type-inference over the as-pattern in two similar function definitions? The Next CEO of Stack OverflowHow do I avoid writing this type of Haskell boilerplate codeHaskell: What is Weak Head Normal Form?Java's Interface and Haskell's type class: differences and similarities?Why is Scala's type inference not as powerful as Haskell's?Need some guidance on function type definitionHow Type inference work in presence of Functional DependenciesGetting associated type synonyms with template HaskellInferring function type from function definition Haskellwhy does my (alternative to !!) function have this typeType inference for polymorphic recursive functionsDefining function signature in GHCi

How to avoid supervisors with prejudiced views?

Is a distribution that is normal, but highly skewed, considered Gaussian?

It it possible to avoid kiwi.com's automatic online check-in and instead do it manually by yourself?

Find the majority element, which appears more than half the time

About implicitly convert type 'int' to 'char', why it is different between `s[i] += s[j]` and `s[i] = s[i]+s[j] `

Traveling with my 5 year old daughter (as the father) without the mother from Germany to Mexico

Percent Dissociated from Titration Curve

Why did early computer designers eschew integers?

How exploitable/balanced is this homebrew spell: Spell Permenancy?

subequations: How to continue numbering within subequation?

Can Sri Krishna be called 'a person'?

Can I use UPS to send my tax returns from abroad to IRS Austin?

DISTINCT column combination with permutations

Is it a bad idea to plug the other end of ESD strap to wall ground?

How should I connect my cat5 cable to connectors having an orange-green line?

Issue with New version of Metamask: Remix cannot detect the Metamask address

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

Car headlights in a world without electricity

Calculate the Mean mean of two numbers

Prodigo = pro + ago?

Simplify trigonometric expression using trigonometric identities

Strange use of "whether ... than ..." in official text

What difference does it make matching a word with/without a trailing whitespace?

Integrating a list of values



Why the difference in type-inference over the as-pattern in two similar function definitions?



The Next CEO of Stack OverflowHow do I avoid writing this type of Haskell boilerplate codeHaskell: What is Weak Head Normal Form?Java's Interface and Haskell's type class: differences and similarities?Why is Scala's type inference not as powerful as Haskell's?Need some guidance on function type definitionHow Type inference work in presence of Functional DependenciesGetting associated type synonyms with template HaskellInferring function type from function definition Haskellwhy does my (alternative to !!) function have this typeType inference for polymorphic recursive functionsDefining function signature in GHCi










23















I have the following two similar function definitions:



left f (Left x) = Left (f x)
left _ (Right x) = Right x

left' f (Left x) = Left (f x)
left' _ r@(Right _) = r


When I check the type signatures of the two functions, I am confused by the following types:



ghci> :t left
left :: (t -> a) -> Either t b -> Either a b
ghci> :t left'
left' :: (a -> a) -> Either a b -> Either a b


I suppose left and left' should be of the same type signature, but the haskell's type inference gives me a suprise.



I can't figure out why the type signatures of left and left' are different. Can anybody give me some information? Thanks!










share|improve this question



















  • 1





    It looks like the first one might be a bit more flexible since t could conceivably equal a.

    – ChaosPandion
    2 days ago






  • 1





    @ChaosPandion yes it is, but that's the mystery (to me as well when I've looked at it!) - it's saying the function input f must have the same input and output type, but there is nothing obvious in the function definition which would so constrain f. In fact the only line which differs in the two definitions doesn't reference f at all!

    – Robin Zigmond
    2 days ago






  • 4





    same thing happens with the definition of fmap for Const btw. the value is repackaged in a different Right/Const constructor (which is polymorphic in the other type).

    – Will Ness
    2 days ago












  • What is this "as-pattern" that you speak of?

    – Peter Mortensen
    yesterday






  • 1





    @PeterMortensen An "as-pattern" is a pattern that uses the @ symbol to assign a value to an identifier while also pattern matching on that value. Here that's r@(Right _)

    – 4castle
    yesterday















23















I have the following two similar function definitions:



left f (Left x) = Left (f x)
left _ (Right x) = Right x

left' f (Left x) = Left (f x)
left' _ r@(Right _) = r


When I check the type signatures of the two functions, I am confused by the following types:



ghci> :t left
left :: (t -> a) -> Either t b -> Either a b
ghci> :t left'
left' :: (a -> a) -> Either a b -> Either a b


I suppose left and left' should be of the same type signature, but the haskell's type inference gives me a suprise.



I can't figure out why the type signatures of left and left' are different. Can anybody give me some information? Thanks!










share|improve this question



















  • 1





    It looks like the first one might be a bit more flexible since t could conceivably equal a.

    – ChaosPandion
    2 days ago






  • 1





    @ChaosPandion yes it is, but that's the mystery (to me as well when I've looked at it!) - it's saying the function input f must have the same input and output type, but there is nothing obvious in the function definition which would so constrain f. In fact the only line which differs in the two definitions doesn't reference f at all!

    – Robin Zigmond
    2 days ago






  • 4





    same thing happens with the definition of fmap for Const btw. the value is repackaged in a different Right/Const constructor (which is polymorphic in the other type).

    – Will Ness
    2 days ago












  • What is this "as-pattern" that you speak of?

    – Peter Mortensen
    yesterday






  • 1





    @PeterMortensen An "as-pattern" is a pattern that uses the @ symbol to assign a value to an identifier while also pattern matching on that value. Here that's r@(Right _)

    – 4castle
    yesterday













23












23








23


1






I have the following two similar function definitions:



left f (Left x) = Left (f x)
left _ (Right x) = Right x

left' f (Left x) = Left (f x)
left' _ r@(Right _) = r


When I check the type signatures of the two functions, I am confused by the following types:



ghci> :t left
left :: (t -> a) -> Either t b -> Either a b
ghci> :t left'
left' :: (a -> a) -> Either a b -> Either a b


I suppose left and left' should be of the same type signature, but the haskell's type inference gives me a suprise.



I can't figure out why the type signatures of left and left' are different. Can anybody give me some information? Thanks!










share|improve this question
















I have the following two similar function definitions:



left f (Left x) = Left (f x)
left _ (Right x) = Right x

left' f (Left x) = Left (f x)
left' _ r@(Right _) = r


When I check the type signatures of the two functions, I am confused by the following types:



ghci> :t left
left :: (t -> a) -> Either t b -> Either a b
ghci> :t left'
left' :: (a -> a) -> Either a b -> Either a b


I suppose left and left' should be of the same type signature, but the haskell's type inference gives me a suprise.



I can't figure out why the type signatures of left and left' are different. Can anybody give me some information? Thanks!







haskell type-signature






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago









TrebledJ

3,48611228




3,48611228










asked 2 days ago









Z-Y.LZ-Y.L

475213




475213







  • 1





    It looks like the first one might be a bit more flexible since t could conceivably equal a.

    – ChaosPandion
    2 days ago






  • 1





    @ChaosPandion yes it is, but that's the mystery (to me as well when I've looked at it!) - it's saying the function input f must have the same input and output type, but there is nothing obvious in the function definition which would so constrain f. In fact the only line which differs in the two definitions doesn't reference f at all!

    – Robin Zigmond
    2 days ago






  • 4





    same thing happens with the definition of fmap for Const btw. the value is repackaged in a different Right/Const constructor (which is polymorphic in the other type).

    – Will Ness
    2 days ago












  • What is this "as-pattern" that you speak of?

    – Peter Mortensen
    yesterday






  • 1





    @PeterMortensen An "as-pattern" is a pattern that uses the @ symbol to assign a value to an identifier while also pattern matching on that value. Here that's r@(Right _)

    – 4castle
    yesterday












  • 1





    It looks like the first one might be a bit more flexible since t could conceivably equal a.

    – ChaosPandion
    2 days ago






  • 1





    @ChaosPandion yes it is, but that's the mystery (to me as well when I've looked at it!) - it's saying the function input f must have the same input and output type, but there is nothing obvious in the function definition which would so constrain f. In fact the only line which differs in the two definitions doesn't reference f at all!

    – Robin Zigmond
    2 days ago






  • 4





    same thing happens with the definition of fmap for Const btw. the value is repackaged in a different Right/Const constructor (which is polymorphic in the other type).

    – Will Ness
    2 days ago












  • What is this "as-pattern" that you speak of?

    – Peter Mortensen
    yesterday






  • 1





    @PeterMortensen An "as-pattern" is a pattern that uses the @ symbol to assign a value to an identifier while also pattern matching on that value. Here that's r@(Right _)

    – 4castle
    yesterday







1




1





It looks like the first one might be a bit more flexible since t could conceivably equal a.

– ChaosPandion
2 days ago





It looks like the first one might be a bit more flexible since t could conceivably equal a.

– ChaosPandion
2 days ago




1




1





@ChaosPandion yes it is, but that's the mystery (to me as well when I've looked at it!) - it's saying the function input f must have the same input and output type, but there is nothing obvious in the function definition which would so constrain f. In fact the only line which differs in the two definitions doesn't reference f at all!

– Robin Zigmond
2 days ago





@ChaosPandion yes it is, but that's the mystery (to me as well when I've looked at it!) - it's saying the function input f must have the same input and output type, but there is nothing obvious in the function definition which would so constrain f. In fact the only line which differs in the two definitions doesn't reference f at all!

– Robin Zigmond
2 days ago




4




4





same thing happens with the definition of fmap for Const btw. the value is repackaged in a different Right/Const constructor (which is polymorphic in the other type).

– Will Ness
2 days ago






same thing happens with the definition of fmap for Const btw. the value is repackaged in a different Right/Const constructor (which is polymorphic in the other type).

– Will Ness
2 days ago














What is this "as-pattern" that you speak of?

– Peter Mortensen
yesterday





What is this "as-pattern" that you speak of?

– Peter Mortensen
yesterday




1




1





@PeterMortensen An "as-pattern" is a pattern that uses the @ symbol to assign a value to an identifier while also pattern matching on that value. Here that's r@(Right _)

– 4castle
yesterday





@PeterMortensen An "as-pattern" is a pattern that uses the @ symbol to assign a value to an identifier while also pattern matching on that value. Here that's r@(Right _)

– 4castle
yesterday












2 Answers
2






active

oldest

votes


















22














In the second line of left':



left' _ r@(Right _) = r
-- ^^^^^^^^^^^ ^


Since you use an as-pattern, you require the input type to be equal to the return type, since clearly they're the exact same value. left''s type is then restricted to something of the form a -> b -> b.



This restriction then propogates backwards to in turn restrict the function's type – hopefully you can see how; it's not too difficult.



However, in the second line of left, you construct a new value



left _ (Right x) = Right x
-- ^^^^^^^


The type of this new value has not been restricted, and thus the same problem doesn't occur; it can be something of the form a -> b -> c, which is what you want.



For this reason, the type of left' is more restricted than the type of left, which is what causes their types to be unequal.




To illustrate this concept more concretely, I will describe to you more precisely how this restriction propogates backwards.



We know that left''s signature is of the form (a -> b) -> Either a q -> Either b q. However, line 2 dictates that Either a q = Either b q, which means that a = b, so the type now becomes (a -> a) -> Either a q -> Either a q.






share|improve this answer




















  • 1





    Related question, borne of the same quirk of types: stackoverflow.com/questions/30859917/…

    – AJFarmar
    2 days ago












  • I get it. Thanks!

    – Z-Y.L
    15 hours ago


















18














The issue here is that there are some "hidden" types which make the difference. The type inference engine can infer those in the first case, but can't in the second case.



When we use



Right :: forall a b. b -> Either a b


we actually need to choose what types a and b are. Fortunately, type inference makes this choice for us in most cases.
Type b is easy to choose: it is the type of the value inside the argument of Right. Type a instead can be anything -- the inference engine has to rely on the context to "force" some choice for a. For instance, note that all of these type check:



test0 :: Either Int Bool
test0 = Right True

test1 :: Either String Bool
test1 = Right True

test2 :: Either [(Char, Int)] Bool
test2 = Right True


Now, in your first function



left :: (t -> a) -> Either t b -> Either a b
left f (Left x) = Left (f x)
left _ (Right x) = Right x


The first matched Right x is actually Right x :: Either t b, where the implicit type arguments are chosen to be t and b. This makes x to have type b.
With this information, the type inference tries to determine the type for the second Right x. There, it can see that it should be of the form Either ?? b since x :: b, but, as it happened for our test examples above, we could use anything for ??. So the type inference engine chooses another type variable a (a type which might be t, but could also be something else).



Instead, in the second function



left' :: (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left (f x)
left' _ r@(Right _) = r


we give a name (r) to the Right _ pattern. As above, that is inferred to have type Either t b. However, now we use the name r on the right of the =, so type inference does not have to infer anything there, and can (in fact, must) simply reuse the type it has already inferred for r. This makes the output type to be the same Either t b as the one for the input, and in turn this forces f to be of type t -> t.



If this is confusing, you could try to completely avoid type inference and provide an explicit choice for the types using the syntax Right @T @U to choose the function U -> Either T U. (You'll need to turn on the ScopedTypeVariables, TypeApplications extensions for this, though.)
Then we can write:



left :: forall t a b. (t -> a) -> Either t b -> Either a b
left f (Left x) = Left @a @b (f x)
left _ (Right x) = Right @a @b x
-- ^^ -- we don't have to pick @t here!


We can also have



left :: forall t b. (t -> t) -> Either t b -> Either t b
left f (Left x) = Left @t @b (f x)
left _ (Right x) = Right @t @b x


and it would work just fine. GHC prefers the first type since it is more general, allowing a to be anything (including t, but also including other types).



There's no type application to specify in the second definition, since it reuses the same value r on the right hand side as on the left:



left' :: forall t b. (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left @t @b (f x)
left' _ r@(Right x) = r
-- ^^ -- can't pick @a here! it's the same as on the LHS





share|improve this answer

























  • Thanks for your detailed explanations!

    – Z-Y.L
    15 hours ago











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55432131%2fwhy-the-difference-in-type-inference-over-the-as-pattern-in-two-similar-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









22














In the second line of left':



left' _ r@(Right _) = r
-- ^^^^^^^^^^^ ^


Since you use an as-pattern, you require the input type to be equal to the return type, since clearly they're the exact same value. left''s type is then restricted to something of the form a -> b -> b.



This restriction then propogates backwards to in turn restrict the function's type – hopefully you can see how; it's not too difficult.



However, in the second line of left, you construct a new value



left _ (Right x) = Right x
-- ^^^^^^^


The type of this new value has not been restricted, and thus the same problem doesn't occur; it can be something of the form a -> b -> c, which is what you want.



For this reason, the type of left' is more restricted than the type of left, which is what causes their types to be unequal.




To illustrate this concept more concretely, I will describe to you more precisely how this restriction propogates backwards.



We know that left''s signature is of the form (a -> b) -> Either a q -> Either b q. However, line 2 dictates that Either a q = Either b q, which means that a = b, so the type now becomes (a -> a) -> Either a q -> Either a q.






share|improve this answer




















  • 1





    Related question, borne of the same quirk of types: stackoverflow.com/questions/30859917/…

    – AJFarmar
    2 days ago












  • I get it. Thanks!

    – Z-Y.L
    15 hours ago















22














In the second line of left':



left' _ r@(Right _) = r
-- ^^^^^^^^^^^ ^


Since you use an as-pattern, you require the input type to be equal to the return type, since clearly they're the exact same value. left''s type is then restricted to something of the form a -> b -> b.



This restriction then propogates backwards to in turn restrict the function's type – hopefully you can see how; it's not too difficult.



However, in the second line of left, you construct a new value



left _ (Right x) = Right x
-- ^^^^^^^


The type of this new value has not been restricted, and thus the same problem doesn't occur; it can be something of the form a -> b -> c, which is what you want.



For this reason, the type of left' is more restricted than the type of left, which is what causes their types to be unequal.




To illustrate this concept more concretely, I will describe to you more precisely how this restriction propogates backwards.



We know that left''s signature is of the form (a -> b) -> Either a q -> Either b q. However, line 2 dictates that Either a q = Either b q, which means that a = b, so the type now becomes (a -> a) -> Either a q -> Either a q.






share|improve this answer




















  • 1





    Related question, borne of the same quirk of types: stackoverflow.com/questions/30859917/…

    – AJFarmar
    2 days ago












  • I get it. Thanks!

    – Z-Y.L
    15 hours ago













22












22








22







In the second line of left':



left' _ r@(Right _) = r
-- ^^^^^^^^^^^ ^


Since you use an as-pattern, you require the input type to be equal to the return type, since clearly they're the exact same value. left''s type is then restricted to something of the form a -> b -> b.



This restriction then propogates backwards to in turn restrict the function's type – hopefully you can see how; it's not too difficult.



However, in the second line of left, you construct a new value



left _ (Right x) = Right x
-- ^^^^^^^


The type of this new value has not been restricted, and thus the same problem doesn't occur; it can be something of the form a -> b -> c, which is what you want.



For this reason, the type of left' is more restricted than the type of left, which is what causes their types to be unequal.




To illustrate this concept more concretely, I will describe to you more precisely how this restriction propogates backwards.



We know that left''s signature is of the form (a -> b) -> Either a q -> Either b q. However, line 2 dictates that Either a q = Either b q, which means that a = b, so the type now becomes (a -> a) -> Either a q -> Either a q.






share|improve this answer















In the second line of left':



left' _ r@(Right _) = r
-- ^^^^^^^^^^^ ^


Since you use an as-pattern, you require the input type to be equal to the return type, since clearly they're the exact same value. left''s type is then restricted to something of the form a -> b -> b.



This restriction then propogates backwards to in turn restrict the function's type – hopefully you can see how; it's not too difficult.



However, in the second line of left, you construct a new value



left _ (Right x) = Right x
-- ^^^^^^^


The type of this new value has not been restricted, and thus the same problem doesn't occur; it can be something of the form a -> b -> c, which is what you want.



For this reason, the type of left' is more restricted than the type of left, which is what causes their types to be unequal.




To illustrate this concept more concretely, I will describe to you more precisely how this restriction propogates backwards.



We know that left''s signature is of the form (a -> b) -> Either a q -> Either b q. However, line 2 dictates that Either a q = Either b q, which means that a = b, so the type now becomes (a -> a) -> Either a q -> Either a q.







share|improve this answer














share|improve this answer



share|improve this answer








edited 2 days ago

























answered 2 days ago









AJFarmarAJFarmar

9,22022854




9,22022854







  • 1





    Related question, borne of the same quirk of types: stackoverflow.com/questions/30859917/…

    – AJFarmar
    2 days ago












  • I get it. Thanks!

    – Z-Y.L
    15 hours ago












  • 1





    Related question, borne of the same quirk of types: stackoverflow.com/questions/30859917/…

    – AJFarmar
    2 days ago












  • I get it. Thanks!

    – Z-Y.L
    15 hours ago







1




1





Related question, borne of the same quirk of types: stackoverflow.com/questions/30859917/…

– AJFarmar
2 days ago






Related question, borne of the same quirk of types: stackoverflow.com/questions/30859917/…

– AJFarmar
2 days ago














I get it. Thanks!

– Z-Y.L
15 hours ago





I get it. Thanks!

– Z-Y.L
15 hours ago













18














The issue here is that there are some "hidden" types which make the difference. The type inference engine can infer those in the first case, but can't in the second case.



When we use



Right :: forall a b. b -> Either a b


we actually need to choose what types a and b are. Fortunately, type inference makes this choice for us in most cases.
Type b is easy to choose: it is the type of the value inside the argument of Right. Type a instead can be anything -- the inference engine has to rely on the context to "force" some choice for a. For instance, note that all of these type check:



test0 :: Either Int Bool
test0 = Right True

test1 :: Either String Bool
test1 = Right True

test2 :: Either [(Char, Int)] Bool
test2 = Right True


Now, in your first function



left :: (t -> a) -> Either t b -> Either a b
left f (Left x) = Left (f x)
left _ (Right x) = Right x


The first matched Right x is actually Right x :: Either t b, where the implicit type arguments are chosen to be t and b. This makes x to have type b.
With this information, the type inference tries to determine the type for the second Right x. There, it can see that it should be of the form Either ?? b since x :: b, but, as it happened for our test examples above, we could use anything for ??. So the type inference engine chooses another type variable a (a type which might be t, but could also be something else).



Instead, in the second function



left' :: (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left (f x)
left' _ r@(Right _) = r


we give a name (r) to the Right _ pattern. As above, that is inferred to have type Either t b. However, now we use the name r on the right of the =, so type inference does not have to infer anything there, and can (in fact, must) simply reuse the type it has already inferred for r. This makes the output type to be the same Either t b as the one for the input, and in turn this forces f to be of type t -> t.



If this is confusing, you could try to completely avoid type inference and provide an explicit choice for the types using the syntax Right @T @U to choose the function U -> Either T U. (You'll need to turn on the ScopedTypeVariables, TypeApplications extensions for this, though.)
Then we can write:



left :: forall t a b. (t -> a) -> Either t b -> Either a b
left f (Left x) = Left @a @b (f x)
left _ (Right x) = Right @a @b x
-- ^^ -- we don't have to pick @t here!


We can also have



left :: forall t b. (t -> t) -> Either t b -> Either t b
left f (Left x) = Left @t @b (f x)
left _ (Right x) = Right @t @b x


and it would work just fine. GHC prefers the first type since it is more general, allowing a to be anything (including t, but also including other types).



There's no type application to specify in the second definition, since it reuses the same value r on the right hand side as on the left:



left' :: forall t b. (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left @t @b (f x)
left' _ r@(Right x) = r
-- ^^ -- can't pick @a here! it's the same as on the LHS





share|improve this answer

























  • Thanks for your detailed explanations!

    – Z-Y.L
    15 hours ago















18














The issue here is that there are some "hidden" types which make the difference. The type inference engine can infer those in the first case, but can't in the second case.



When we use



Right :: forall a b. b -> Either a b


we actually need to choose what types a and b are. Fortunately, type inference makes this choice for us in most cases.
Type b is easy to choose: it is the type of the value inside the argument of Right. Type a instead can be anything -- the inference engine has to rely on the context to "force" some choice for a. For instance, note that all of these type check:



test0 :: Either Int Bool
test0 = Right True

test1 :: Either String Bool
test1 = Right True

test2 :: Either [(Char, Int)] Bool
test2 = Right True


Now, in your first function



left :: (t -> a) -> Either t b -> Either a b
left f (Left x) = Left (f x)
left _ (Right x) = Right x


The first matched Right x is actually Right x :: Either t b, where the implicit type arguments are chosen to be t and b. This makes x to have type b.
With this information, the type inference tries to determine the type for the second Right x. There, it can see that it should be of the form Either ?? b since x :: b, but, as it happened for our test examples above, we could use anything for ??. So the type inference engine chooses another type variable a (a type which might be t, but could also be something else).



Instead, in the second function



left' :: (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left (f x)
left' _ r@(Right _) = r


we give a name (r) to the Right _ pattern. As above, that is inferred to have type Either t b. However, now we use the name r on the right of the =, so type inference does not have to infer anything there, and can (in fact, must) simply reuse the type it has already inferred for r. This makes the output type to be the same Either t b as the one for the input, and in turn this forces f to be of type t -> t.



If this is confusing, you could try to completely avoid type inference and provide an explicit choice for the types using the syntax Right @T @U to choose the function U -> Either T U. (You'll need to turn on the ScopedTypeVariables, TypeApplications extensions for this, though.)
Then we can write:



left :: forall t a b. (t -> a) -> Either t b -> Either a b
left f (Left x) = Left @a @b (f x)
left _ (Right x) = Right @a @b x
-- ^^ -- we don't have to pick @t here!


We can also have



left :: forall t b. (t -> t) -> Either t b -> Either t b
left f (Left x) = Left @t @b (f x)
left _ (Right x) = Right @t @b x


and it would work just fine. GHC prefers the first type since it is more general, allowing a to be anything (including t, but also including other types).



There's no type application to specify in the second definition, since it reuses the same value r on the right hand side as on the left:



left' :: forall t b. (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left @t @b (f x)
left' _ r@(Right x) = r
-- ^^ -- can't pick @a here! it's the same as on the LHS





share|improve this answer

























  • Thanks for your detailed explanations!

    – Z-Y.L
    15 hours ago













18












18








18







The issue here is that there are some "hidden" types which make the difference. The type inference engine can infer those in the first case, but can't in the second case.



When we use



Right :: forall a b. b -> Either a b


we actually need to choose what types a and b are. Fortunately, type inference makes this choice for us in most cases.
Type b is easy to choose: it is the type of the value inside the argument of Right. Type a instead can be anything -- the inference engine has to rely on the context to "force" some choice for a. For instance, note that all of these type check:



test0 :: Either Int Bool
test0 = Right True

test1 :: Either String Bool
test1 = Right True

test2 :: Either [(Char, Int)] Bool
test2 = Right True


Now, in your first function



left :: (t -> a) -> Either t b -> Either a b
left f (Left x) = Left (f x)
left _ (Right x) = Right x


The first matched Right x is actually Right x :: Either t b, where the implicit type arguments are chosen to be t and b. This makes x to have type b.
With this information, the type inference tries to determine the type for the second Right x. There, it can see that it should be of the form Either ?? b since x :: b, but, as it happened for our test examples above, we could use anything for ??. So the type inference engine chooses another type variable a (a type which might be t, but could also be something else).



Instead, in the second function



left' :: (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left (f x)
left' _ r@(Right _) = r


we give a name (r) to the Right _ pattern. As above, that is inferred to have type Either t b. However, now we use the name r on the right of the =, so type inference does not have to infer anything there, and can (in fact, must) simply reuse the type it has already inferred for r. This makes the output type to be the same Either t b as the one for the input, and in turn this forces f to be of type t -> t.



If this is confusing, you could try to completely avoid type inference and provide an explicit choice for the types using the syntax Right @T @U to choose the function U -> Either T U. (You'll need to turn on the ScopedTypeVariables, TypeApplications extensions for this, though.)
Then we can write:



left :: forall t a b. (t -> a) -> Either t b -> Either a b
left f (Left x) = Left @a @b (f x)
left _ (Right x) = Right @a @b x
-- ^^ -- we don't have to pick @t here!


We can also have



left :: forall t b. (t -> t) -> Either t b -> Either t b
left f (Left x) = Left @t @b (f x)
left _ (Right x) = Right @t @b x


and it would work just fine. GHC prefers the first type since it is more general, allowing a to be anything (including t, but also including other types).



There's no type application to specify in the second definition, since it reuses the same value r on the right hand side as on the left:



left' :: forall t b. (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left @t @b (f x)
left' _ r@(Right x) = r
-- ^^ -- can't pick @a here! it's the same as on the LHS





share|improve this answer















The issue here is that there are some "hidden" types which make the difference. The type inference engine can infer those in the first case, but can't in the second case.



When we use



Right :: forall a b. b -> Either a b


we actually need to choose what types a and b are. Fortunately, type inference makes this choice for us in most cases.
Type b is easy to choose: it is the type of the value inside the argument of Right. Type a instead can be anything -- the inference engine has to rely on the context to "force" some choice for a. For instance, note that all of these type check:



test0 :: Either Int Bool
test0 = Right True

test1 :: Either String Bool
test1 = Right True

test2 :: Either [(Char, Int)] Bool
test2 = Right True


Now, in your first function



left :: (t -> a) -> Either t b -> Either a b
left f (Left x) = Left (f x)
left _ (Right x) = Right x


The first matched Right x is actually Right x :: Either t b, where the implicit type arguments are chosen to be t and b. This makes x to have type b.
With this information, the type inference tries to determine the type for the second Right x. There, it can see that it should be of the form Either ?? b since x :: b, but, as it happened for our test examples above, we could use anything for ??. So the type inference engine chooses another type variable a (a type which might be t, but could also be something else).



Instead, in the second function



left' :: (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left (f x)
left' _ r@(Right _) = r


we give a name (r) to the Right _ pattern. As above, that is inferred to have type Either t b. However, now we use the name r on the right of the =, so type inference does not have to infer anything there, and can (in fact, must) simply reuse the type it has already inferred for r. This makes the output type to be the same Either t b as the one for the input, and in turn this forces f to be of type t -> t.



If this is confusing, you could try to completely avoid type inference and provide an explicit choice for the types using the syntax Right @T @U to choose the function U -> Either T U. (You'll need to turn on the ScopedTypeVariables, TypeApplications extensions for this, though.)
Then we can write:



left :: forall t a b. (t -> a) -> Either t b -> Either a b
left f (Left x) = Left @a @b (f x)
left _ (Right x) = Right @a @b x
-- ^^ -- we don't have to pick @t here!


We can also have



left :: forall t b. (t -> t) -> Either t b -> Either t b
left f (Left x) = Left @t @b (f x)
left _ (Right x) = Right @t @b x


and it would work just fine. GHC prefers the first type since it is more general, allowing a to be anything (including t, but also including other types).



There's no type application to specify in the second definition, since it reuses the same value r on the right hand side as on the left:



left' :: forall t b. (t -> t) -> Either t b -> Either t b
left' f (Left x) = Left @t @b (f x)
left' _ r@(Right x) = r
-- ^^ -- can't pick @a here! it's the same as on the LHS






share|improve this answer














share|improve this answer



share|improve this answer








edited 2 days ago









A Tayler

2983




2983










answered 2 days ago









chichi

77.3k287146




77.3k287146












  • Thanks for your detailed explanations!

    – Z-Y.L
    15 hours ago

















  • Thanks for your detailed explanations!

    – Z-Y.L
    15 hours ago
















Thanks for your detailed explanations!

– Z-Y.L
15 hours ago





Thanks for your detailed explanations!

– Z-Y.L
15 hours ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55432131%2fwhy-the-difference-in-type-inference-over-the-as-pattern-in-two-similar-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Romeo and Juliet ContentsCharactersSynopsisSourcesDate and textThemes and motifsCriticism and interpretationLegacyScene by sceneSee alsoNotes and referencesSourcesExternal linksNavigation menu"Consumer Price Index (estimate) 1800–"10.2307/28710160037-3222287101610.1093/res/II.5.31910.2307/45967845967810.2307/2869925286992510.1525/jams.1982.35.3.03a00050"Dada Masilo: South African dancer who breaks the rules"10.1093/res/os-XV.57.1610.2307/28680942868094"Sweet Sorrow: Mann-Korman's Romeo and Juliet Closes Sept. 5 at MN's Ordway"the original10.2307/45957745957710.1017/CCOL0521570476.009"Ram Leela box office collections hit massive Rs 100 crore, pulverises prediction"Archived"Broadway Revival of Romeo and Juliet, Starring Orlando Bloom and Condola Rashad, Will Close Dec. 8"Archived10.1075/jhp.7.1.04hon"Wherefore art thou, Romeo? To make us laugh at Navy Pier"the original10.1093/gmo/9781561592630.article.O006772"Ram-leela Review Roundup: Critics Hail Film as Best Adaptation of Romeo and Juliet"Archived10.2307/31946310047-77293194631"Romeo and Juliet get Twitter treatment""Juliet's Nurse by Lois Leveen""Romeo and Juliet: Orlando Bloom's Broadway Debut Released in Theaters for Valentine's Day"Archived"Romeo and Juliet Has No Balcony"10.1093/gmo/9781561592630.article.O00778110.2307/2867423286742310.1076/enst.82.2.115.959510.1080/00138380601042675"A plague o' both your houses: error in GCSE exam paper forces apology""Juliet of the Five O'Clock Shadow, and Other Wonders"10.2307/33912430027-4321339124310.2307/28487440038-7134284874410.2307/29123140149-661129123144728341M"Weekender Guide: Shakespeare on The Drive""balcony"UK public library membership"romeo"UK public library membership10.1017/CCOL9780521844291"Post-Zionist Critique on Israel and the Palestinians Part III: Popular Culture"10.2307/25379071533-86140377-919X2537907"Capulets and Montagues: UK exam board admit mixing names up in Romeo and Juliet paper"Istoria Novellamente Ritrovata di Due Nobili Amanti2027/mdp.390150822329610820-750X"GCSE exam error: Board accidentally rewrites Shakespeare"10.2307/29176390149-66112917639"Exam board apologises after error in English GCSE paper which confused characters in Shakespeare's Romeo and Juliet""From Mariotto and Ganozza to Romeo and Guilietta: Metamorphoses of a Renaissance Tale"10.2307/37323537323510.2307/2867455286745510.2307/28678912867891"10 Questions for Taylor Swift"10.2307/28680922868092"Haymarket Theatre""The Zeffirelli Way: Revealing Talk by Florentine Director""Michael Smuin: 1938-2007 / Prolific dance director had showy career"The Life and Art of Edwin BoothRomeo and JulietRomeo and JulietRomeo and JulietRomeo and JulietEasy Read Romeo and JulietRomeo and Julieteeecb12003684p(data)4099369-3n8211610759dbe00d-a9e2-41a3-b2c1-977dd692899302814385X313670221313670221

Crop image to path created in TikZ? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Crop an inserted image?TikZ pictures does not appear in posterImage behind and beyond crop marks?Tikz picture as large as possible on A4 PageTransparency vs image compression dilemmaHow to crop background from image automatically?Image does not cropTikzexternal capturing crop marks when externalizing pgfplots?How to include image path that contains a dollar signCrop image with left size given

Creating closest line along the point''s azimuth using PostgreSQL Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Drawing line between points at specific distance in PostGIS?How to efficiently find the closest point over the dateline?How to find the nearest point by using PostGIS function?PostGIS nearest point with LATERAL JOIN in PostgreSQL 9.3+Creating a table and inserting selected streets using plpgsql functionsCreating a table that stores Distances and other columnSaving select query results (year wise) from PostgreSQL/PostGIS to text filesWhat is the information behind this geometry?How to give start and end vertex ids dynamically in pgr_dijkstra?Point to Polygon nearest distance DS_distance is not using geography index & knn <-> or <#> does not give result in orderLine to point conversion with start point and end point detection?