Why the difference in type-inference over the as-pattern in two similar function definitions?How 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

Why would a military not separate its forces into different branches?

Where to draw the line between quantum mechanics theory and its interpretation(s)?

getline() vs. fgets(): Control memory allocation

Why is "breaking the mould" positively connoted?

Removing racism on a multi raced world

Is there an age requirement to play in Adventurers League?

Endgame puzzle: How to avoid stalemate and win?

Hostile Divisor Numbers

Seeing 2 very different execution plans for an UPDATE between test & prod environments

Nested loops to process groups of pictures

Is there a word for food that's gone 'bad', but is still edible?

Install LibreOffice-Writer Only not LibreOffice whole package

What do "Sech" and "Vich" mean in this sentence?

Find magical solution to magical equation

Will 700 more planes a day fly because of the Heathrow expansion?

Is disk brake effectiveness mitigated by tyres losing traction under strong braking?

How do LIGO and VIRGO know that a gravitational wave has its origin in a neutron star or a black hole?

What was the first story to feature the plot "the monsters were human all along"?

How can I get people to remember my character's gender?

Why do people keep telling me that I am a bad photographer?

As a GM, is it bad form to ask for a moment to think when improvising?

How to ask systemd to not start a system service on boot?

Gladys unchained

Is the book wrong about the Nyquist sampling cirteria?



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


How 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






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








26















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
    Mar 30 at 14:00






  • 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
    Mar 30 at 14:01






  • 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
    Mar 30 at 15:02












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

    – Peter Mortensen
    Mar 30 at 21:24






  • 2





    @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
    Mar 31 at 4:33

















26















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
    Mar 30 at 14:00






  • 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
    Mar 30 at 14:01






  • 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
    Mar 30 at 15:02












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

    – Peter Mortensen
    Mar 30 at 21:24






  • 2





    @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
    Mar 31 at 4:33













26












26








26


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 Mar 30 at 14:18









TrebledJ

4,11721432




4,11721432










asked Mar 30 at 13:54









Z-Y.LZ-Y.L

512314




512314







  • 1





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

    – ChaosPandion
    Mar 30 at 14:00






  • 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
    Mar 30 at 14:01






  • 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
    Mar 30 at 15:02












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

    – Peter Mortensen
    Mar 30 at 21:24






  • 2





    @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
    Mar 31 at 4:33












  • 1





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

    – ChaosPandion
    Mar 30 at 14:00






  • 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
    Mar 30 at 14:01






  • 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
    Mar 30 at 15:02












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

    – Peter Mortensen
    Mar 30 at 21:24






  • 2





    @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
    Mar 31 at 4:33







1




1





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

– ChaosPandion
Mar 30 at 14:00





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

– ChaosPandion
Mar 30 at 14:00




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
Mar 30 at 14:01





@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
Mar 30 at 14:01




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
Mar 30 at 15:02






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
Mar 30 at 15:02














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

– Peter Mortensen
Mar 30 at 21:24





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

– Peter Mortensen
Mar 30 at 21:24




2




2





@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
Mar 31 at 4:33





@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
Mar 31 at 4:33












2 Answers
2






active

oldest

votes


















25














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
    Mar 30 at 14:19



















19














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
    Apr 1 at 4:22











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









25














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
    Mar 30 at 14:19
















25














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
    Mar 30 at 14:19














25












25








25







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 Mar 30 at 14:28

























answered Mar 30 at 14:07









AJFarmarAJFarmar

9,47622954




9,47622954







  • 1





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

    – AJFarmar
    Mar 30 at 14:19













  • 1





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

    – AJFarmar
    Mar 30 at 14:19








1




1





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

– AJFarmar
Mar 30 at 14:19






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

– AJFarmar
Mar 30 at 14:19














19














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
    Apr 1 at 4:22















19














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
    Apr 1 at 4:22













19












19








19







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 Mar 30 at 18:39









moonGoose

77619




77619










answered Mar 30 at 14:27









chichi

78.3k288148




78.3k288148












  • Thanks for your detailed explanations!

    – Z-Y.L
    Apr 1 at 4:22

















  • Thanks for your detailed explanations!

    – Z-Y.L
    Apr 1 at 4:22
















Thanks for your detailed explanations!

– Z-Y.L
Apr 1 at 4:22





Thanks for your detailed explanations!

– Z-Y.L
Apr 1 at 4:22

















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

Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum

He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

Slayer Innehåll Historia | Stil, komposition och lyrik | Bandets betydelse och framgångar | Sidoprojekt och samarbeten | Kontroverser | Medlemmar | Utmärkelser och nomineringar | Turnéer och festivaler | Diskografi | Referenser | Externa länkar | Navigeringsmenywww.slayer.net”Metal Massacre vol. 1””Metal Massacre vol. 3””Metal Massacre Volume III””Show No Mercy””Haunting the Chapel””Live Undead””Hell Awaits””Reign in Blood””Reign in Blood””Gold & Platinum – Reign in Blood””Golden Gods Awards Winners”originalet”Kerrang! Hall Of Fame””Slayer Looks Back On 37-Year Career In New Video Series: Part Two””South of Heaven””Gold & Platinum – South of Heaven””Seasons in the Abyss””Gold & Platinum - Seasons in the Abyss””Divine Intervention””Divine Intervention - Release group by Slayer””Gold & Platinum - Divine Intervention””Live Intrusion””Undisputed Attitude””Abolish Government/Superficial Love””Release “Slatanic Slaughter: A Tribute to Slayer” by Various Artists””Diabolus in Musica””Soundtrack to the Apocalypse””God Hates Us All””Systematic - Relationships””War at the Warfield””Gold & Platinum - War at the Warfield””Soundtrack to the Apocalypse””Gold & Platinum - Still Reigning””Metallica, Slayer, Iron Mauden Among Winners At Metal Hammer Awards””Eternal Pyre””Eternal Pyre - Slayer release group””Eternal Pyre””Metal Storm Awards 2006””Kerrang! Hall Of Fame””Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Bullet-For My Valentine booed at Metal Hammer Golden Gods Awards””Unholy Aliance””The End Of Slayer?””Slayer: We Could Thrash Out Two More Albums If We're Fast Enough...””'The Unholy Alliance: Chapter III' UK Dates Added”originalet”Megadeth And Slayer To Co-Headline 'Canadian Carnage' Trek”originalet”World Painted Blood””Release “World Painted Blood” by Slayer””Metallica Heading To Cinemas””Slayer, Megadeth To Join Forces For 'European Carnage' Tour - Dec. 18, 2010”originalet”Slayer's Hanneman Contracts Acute Infection; Band To Bring In Guest Guitarist””Cannibal Corpse's Pat O'Brien Will Step In As Slayer's Guest Guitarist”originalet”Slayer’s Jeff Hanneman Dead at 49””Dave Lombardo Says He Made Only $67,000 In 2011 While Touring With Slayer””Slayer: We Do Not Agree With Dave Lombardo's Substance Or Timeline Of Events””Slayer Welcomes Drummer Paul Bostaph Back To The Fold””Slayer Hope to Unveil Never-Before-Heard Jeff Hanneman Material on Next Album””Slayer Debut New Song 'Implode' During Surprise Golden Gods Appearance””Release group Repentless by Slayer””Repentless - Slayer - Credits””Slayer””Metal Storm Awards 2015””Slayer - to release comic book "Repentless #1"””Slayer To Release 'Repentless' 6.66" Vinyl Box Set””BREAKING NEWS: Slayer Announce Farewell Tour””Slayer Recruit Lamb of God, Anthrax, Behemoth + Testament for Final Tour””Slayer lägger ner efter 37 år””Slayer Announces Second North American Leg Of 'Final' Tour””Final World Tour””Slayer Announces Final European Tour With Lamb of God, Anthrax And Obituary””Slayer To Tour Europe With Lamb of God, Anthrax And Obituary””Slayer To Play 'Last French Show Ever' At Next Year's Hellfst””Slayer's Final World Tour Will Extend Into 2019””Death Angel's Rob Cavestany On Slayer's 'Farewell' Tour: 'Some Of Us Could See This Coming'””Testament Has No Plans To Retire Anytime Soon, Says Chuck Billy””Anthrax's Scott Ian On Slayer's 'Farewell' Tour Plans: 'I Was Surprised And I Wasn't Surprised'””Slayer””Slayer's Morbid Schlock””Review/Rock; For Slayer, the Mania Is the Message””Slayer - Biography””Slayer - Reign In Blood”originalet”Dave Lombardo””An exclusive oral history of Slayer”originalet”Exclusive! Interview With Slayer Guitarist Jeff Hanneman”originalet”Thinking Out Loud: Slayer's Kerry King on hair metal, Satan and being polite””Slayer Lyrics””Slayer - Biography””Most influential artists for extreme metal music””Slayer - Reign in Blood””Slayer guitarist Jeff Hanneman dies aged 49””Slatanic Slaughter: A Tribute to Slayer””Gateway to Hell: A Tribute to Slayer””Covered In Blood””Slayer: The Origins of Thrash in San Francisco, CA.””Why They Rule - #6 Slayer”originalet”Guitar World's 100 Greatest Heavy Metal Guitarists Of All Time”originalet”The fans have spoken: Slayer comes out on top in readers' polls”originalet”Tribute to Jeff Hanneman (1964-2013)””Lamb Of God Frontman: We Sound Like A Slayer Rip-Off””BEHEMOTH Frontman Pays Tribute To SLAYER's JEFF HANNEMAN””Slayer, Hatebreed Doing Double Duty On This Year's Ozzfest””System of a Down””Lacuna Coil’s Andrea Ferro Talks Influences, Skateboarding, Band Origins + More””Slayer - Reign in Blood””Into The Lungs of Hell””Slayer rules - en utställning om fans””Slayer and Their Fans Slashed Through a No-Holds-Barred Night at Gas Monkey””Home””Slayer””Gold & Platinum - The Big 4 Live from Sofia, Bulgaria””Exclusive! Interview With Slayer Guitarist Kerry King””2008-02-23: Wiltern, Los Angeles, CA, USA””Slayer's Kerry King To Perform With Megadeth Tonight! - Oct. 21, 2010”originalet”Dave Lombardo - Biography”Slayer Case DismissedArkiveradUltimate Classic Rock: Slayer guitarist Jeff Hanneman dead at 49.”Slayer: "We could never do any thing like Some Kind Of Monster..."””Cannibal Corpse'S Pat O'Brien Will Step In As Slayer'S Guest Guitarist | The Official Slayer Site”originalet”Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Kerrang! Awards 2006 Blog: Kerrang! Hall Of Fame””Kerrang! Awards 2013: Kerrang! Legend”originalet”Metallica, Slayer, Iron Maien Among Winners At Metal Hammer Awards””Metal Hammer Golden Gods Awards””Bullet For My Valentine Booed At Metal Hammer Golden Gods Awards””Metal Storm Awards 2006””Metal Storm Awards 2015””Slayer's Concert History””Slayer - Relationships””Slayer - Releases”Slayers officiella webbplatsSlayer på MusicBrainzOfficiell webbplatsSlayerSlayerr1373445760000 0001 1540 47353068615-5086262726cb13906545x(data)6033143kn20030215029