Why does GHC infer a monomorphic type here, even with MonomorphismRestriction disabled? The Next CEO of Stack OverflowResolving the type of `f = f (<*>) pure`NoMonomorphismRestriction helps preserve sharing?How can eta-reduction of a well typed function result in a type error?Can I write such polymorphic function? What language extensions do I need?GHC rewrite rule specialising a function for a type classType Inference in PatternsHow to type check recursive definitions using Algorithm W?What is the monomorphism restriction?Why are higher rank types so fragile in HaskellWhy can't GHC typecheck this function involving polymorphism and existential types?Problems With Type Inference on (^)

Does it take more energy to get to Venus or to Mars?

declare as function pointer and initialize in the same line

Is HostGator storing my password in plaintext?

Return of the Riley Riddles in Reverse

India just shot down a satellite from the ground. At what altitude range is the resulting debris field?

suction cup thing with 1/4 TRS cable?

Was a professor correct to chastise me for writing "Prof. X" rather than "Professor X"?

If the heap is initialized for security, then why is the stack uninitialized?

How easy is it to start Magic from scratch?

ls Ordering[Ordering[list]] optimal?

Fastest way to shutdown Ubuntu Mate 18.10

What makes a siege story/plot interesting?

How can I open an app using Terminal?

Why here is plural "We went to the movies last night."

MAZDA 3 2006 (UK) - poor acceleration then takes off at 3250 revs

Why is there a PLL in CPU?

Does the Brexit deal have to be agreed by both Houses?

WOW air has ceased operation, can I get my tickets refunded?

How to make a variable always equal to the result of some calculations?

Trouble understanding the speech of overseas colleagues

How long to clear the 'suck zone' of a turbofan after start is initiated?

I believe this to be a fraud

Is there a good way to store credentials outside of a password manager?

The King's new dress



Why does GHC infer a monomorphic type here, even with MonomorphismRestriction disabled?



The Next CEO of Stack OverflowResolving the type of `f = f (<*>) pure`NoMonomorphismRestriction helps preserve sharing?How can eta-reduction of a well typed function result in a type error?Can I write such polymorphic function? What language extensions do I need?GHC rewrite rule specialising a function for a type classType Inference in PatternsHow to type check recursive definitions using Algorithm W?What is the monomorphism restriction?Why are higher rank types so fragile in HaskellWhy can't GHC typecheck this function involving polymorphism and existential types?Problems With Type Inference on (^)










13















This was prompted by Resolving the type of `f = f (<*>) pure`, which discusses a more complicated example, but this one works too.



The following definition compiles without problem:



w :: Integral a => a
w = fromInteger w


...Of course it doesn't work runtime-wise, but that's beside the question. The point is that the definition of w itself uses a specialised version of w :: Integer. Clearly that is a suitable instantiation, and therefore typechecks.



However, if we remove the signature, then GHC infers not the above type, but only the concrete one:



w' = fromInteger w'


GHCi> :t w
w :: Integral a => a
GHCi> :t w'
w' :: Integer


Well, when I saw this, I was fairly sure this was the monomorphism restriction at work. It's well known that also e.g.



i = 3


GHCi> :t i
i :: Integer


although i :: Num p => p would be perfectly possible. And indeed, i :: Num p => p is inferred if -XNoMonomorphismRestriction is active, i.e. if the monomorphism restriction is disabled.



However, in case of w' only the type Integer is inferred even when the monomorphism restriction is disabled.



To count out that this has something to do with defaulting:



fromFloat :: RealFrac a => Float -> a
q :: RealFrac a => a
q = fromFloat q
q' = fromFloat q'


GHCi> :t q
q :: RealFrac a => a
GHCi> :t q'
q' :: Float


Why is the polymorphic type not inferred?










share|improve this question
























  • Doesn't the monomorphism restriction apply only to simple bindings anyways (and w' = fromInteger w', being recursive, is not simple)?

    – Alec
    4 hours ago











  • @Alec possible, but still – why does something like the monomorphism restriction seem to kick in here?

    – leftaroundabout
    4 hours ago











  • I'm probably being dense and missing something here, but fromInteger has type (Num a) => Integer -> a, and since w' is used as the input to fromInteger, doesn't that mean Integer is the only possible type for it? Indeed I'm rather surprised that the version with the polymorphic type signature compiles. (So as I said, probably missing something.)

    – Robin Zigmond
    4 hours ago











  • @RobinZigmond Integer is certainly the only possible monomorphic type for w', but as w demonstrates a polymorphic type is perfectly fine as well. After all, a polymorphic type can be instantiated to a monomorphic one, provided it fulfills the constraints.

    – leftaroundabout
    4 hours ago
















13















This was prompted by Resolving the type of `f = f (<*>) pure`, which discusses a more complicated example, but this one works too.



The following definition compiles without problem:



w :: Integral a => a
w = fromInteger w


...Of course it doesn't work runtime-wise, but that's beside the question. The point is that the definition of w itself uses a specialised version of w :: Integer. Clearly that is a suitable instantiation, and therefore typechecks.



However, if we remove the signature, then GHC infers not the above type, but only the concrete one:



w' = fromInteger w'


GHCi> :t w
w :: Integral a => a
GHCi> :t w'
w' :: Integer


Well, when I saw this, I was fairly sure this was the monomorphism restriction at work. It's well known that also e.g.



i = 3


GHCi> :t i
i :: Integer


although i :: Num p => p would be perfectly possible. And indeed, i :: Num p => p is inferred if -XNoMonomorphismRestriction is active, i.e. if the monomorphism restriction is disabled.



However, in case of w' only the type Integer is inferred even when the monomorphism restriction is disabled.



To count out that this has something to do with defaulting:



fromFloat :: RealFrac a => Float -> a
q :: RealFrac a => a
q = fromFloat q
q' = fromFloat q'


GHCi> :t q
q :: RealFrac a => a
GHCi> :t q'
q' :: Float


Why is the polymorphic type not inferred?










share|improve this question
























  • Doesn't the monomorphism restriction apply only to simple bindings anyways (and w' = fromInteger w', being recursive, is not simple)?

    – Alec
    4 hours ago











  • @Alec possible, but still – why does something like the monomorphism restriction seem to kick in here?

    – leftaroundabout
    4 hours ago











  • I'm probably being dense and missing something here, but fromInteger has type (Num a) => Integer -> a, and since w' is used as the input to fromInteger, doesn't that mean Integer is the only possible type for it? Indeed I'm rather surprised that the version with the polymorphic type signature compiles. (So as I said, probably missing something.)

    – Robin Zigmond
    4 hours ago











  • @RobinZigmond Integer is certainly the only possible monomorphic type for w', but as w demonstrates a polymorphic type is perfectly fine as well. After all, a polymorphic type can be instantiated to a monomorphic one, provided it fulfills the constraints.

    – leftaroundabout
    4 hours ago














13












13








13


2






This was prompted by Resolving the type of `f = f (<*>) pure`, which discusses a more complicated example, but this one works too.



The following definition compiles without problem:



w :: Integral a => a
w = fromInteger w


...Of course it doesn't work runtime-wise, but that's beside the question. The point is that the definition of w itself uses a specialised version of w :: Integer. Clearly that is a suitable instantiation, and therefore typechecks.



However, if we remove the signature, then GHC infers not the above type, but only the concrete one:



w' = fromInteger w'


GHCi> :t w
w :: Integral a => a
GHCi> :t w'
w' :: Integer


Well, when I saw this, I was fairly sure this was the monomorphism restriction at work. It's well known that also e.g.



i = 3


GHCi> :t i
i :: Integer


although i :: Num p => p would be perfectly possible. And indeed, i :: Num p => p is inferred if -XNoMonomorphismRestriction is active, i.e. if the monomorphism restriction is disabled.



However, in case of w' only the type Integer is inferred even when the monomorphism restriction is disabled.



To count out that this has something to do with defaulting:



fromFloat :: RealFrac a => Float -> a
q :: RealFrac a => a
q = fromFloat q
q' = fromFloat q'


GHCi> :t q
q :: RealFrac a => a
GHCi> :t q'
q' :: Float


Why is the polymorphic type not inferred?










share|improve this question
















This was prompted by Resolving the type of `f = f (<*>) pure`, which discusses a more complicated example, but this one works too.



The following definition compiles without problem:



w :: Integral a => a
w = fromInteger w


...Of course it doesn't work runtime-wise, but that's beside the question. The point is that the definition of w itself uses a specialised version of w :: Integer. Clearly that is a suitable instantiation, and therefore typechecks.



However, if we remove the signature, then GHC infers not the above type, but only the concrete one:



w' = fromInteger w'


GHCi> :t w
w :: Integral a => a
GHCi> :t w'
w' :: Integer


Well, when I saw this, I was fairly sure this was the monomorphism restriction at work. It's well known that also e.g.



i = 3


GHCi> :t i
i :: Integer


although i :: Num p => p would be perfectly possible. And indeed, i :: Num p => p is inferred if -XNoMonomorphismRestriction is active, i.e. if the monomorphism restriction is disabled.



However, in case of w' only the type Integer is inferred even when the monomorphism restriction is disabled.



To count out that this has something to do with defaulting:



fromFloat :: RealFrac a => Float -> a
q :: RealFrac a => a
q = fromFloat q
q' = fromFloat q'


GHCi> :t q
q :: RealFrac a => a
GHCi> :t q'
q' :: Float


Why is the polymorphic type not inferred?







haskell recursion type-inference parametric-polymorphism






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 hours ago







leftaroundabout

















asked 4 hours ago









leftaroundaboutleftaroundabout

80.1k3119237




80.1k3119237












  • Doesn't the monomorphism restriction apply only to simple bindings anyways (and w' = fromInteger w', being recursive, is not simple)?

    – Alec
    4 hours ago











  • @Alec possible, but still – why does something like the monomorphism restriction seem to kick in here?

    – leftaroundabout
    4 hours ago











  • I'm probably being dense and missing something here, but fromInteger has type (Num a) => Integer -> a, and since w' is used as the input to fromInteger, doesn't that mean Integer is the only possible type for it? Indeed I'm rather surprised that the version with the polymorphic type signature compiles. (So as I said, probably missing something.)

    – Robin Zigmond
    4 hours ago











  • @RobinZigmond Integer is certainly the only possible monomorphic type for w', but as w demonstrates a polymorphic type is perfectly fine as well. After all, a polymorphic type can be instantiated to a monomorphic one, provided it fulfills the constraints.

    – leftaroundabout
    4 hours ago


















  • Doesn't the monomorphism restriction apply only to simple bindings anyways (and w' = fromInteger w', being recursive, is not simple)?

    – Alec
    4 hours ago











  • @Alec possible, but still – why does something like the monomorphism restriction seem to kick in here?

    – leftaroundabout
    4 hours ago











  • I'm probably being dense and missing something here, but fromInteger has type (Num a) => Integer -> a, and since w' is used as the input to fromInteger, doesn't that mean Integer is the only possible type for it? Indeed I'm rather surprised that the version with the polymorphic type signature compiles. (So as I said, probably missing something.)

    – Robin Zigmond
    4 hours ago











  • @RobinZigmond Integer is certainly the only possible monomorphic type for w', but as w demonstrates a polymorphic type is perfectly fine as well. After all, a polymorphic type can be instantiated to a monomorphic one, provided it fulfills the constraints.

    – leftaroundabout
    4 hours ago

















Doesn't the monomorphism restriction apply only to simple bindings anyways (and w' = fromInteger w', being recursive, is not simple)?

– Alec
4 hours ago





Doesn't the monomorphism restriction apply only to simple bindings anyways (and w' = fromInteger w', being recursive, is not simple)?

– Alec
4 hours ago













@Alec possible, but still – why does something like the monomorphism restriction seem to kick in here?

– leftaroundabout
4 hours ago





@Alec possible, but still – why does something like the monomorphism restriction seem to kick in here?

– leftaroundabout
4 hours ago













I'm probably being dense and missing something here, but fromInteger has type (Num a) => Integer -> a, and since w' is used as the input to fromInteger, doesn't that mean Integer is the only possible type for it? Indeed I'm rather surprised that the version with the polymorphic type signature compiles. (So as I said, probably missing something.)

– Robin Zigmond
4 hours ago





I'm probably being dense and missing something here, but fromInteger has type (Num a) => Integer -> a, and since w' is used as the input to fromInteger, doesn't that mean Integer is the only possible type for it? Indeed I'm rather surprised that the version with the polymorphic type signature compiles. (So as I said, probably missing something.)

– Robin Zigmond
4 hours ago













@RobinZigmond Integer is certainly the only possible monomorphic type for w', but as w demonstrates a polymorphic type is perfectly fine as well. After all, a polymorphic type can be instantiated to a monomorphic one, provided it fulfills the constraints.

– leftaroundabout
4 hours ago






@RobinZigmond Integer is certainly the only possible monomorphic type for w', but as w demonstrates a polymorphic type is perfectly fine as well. After all, a polymorphic type can be instantiated to a monomorphic one, provided it fulfills the constraints.

– leftaroundabout
4 hours ago













1 Answer
1






active

oldest

votes


















13














Polymorphic recursion (where a function calls itself at a different type than the one at which it was called) always requires a type signature. The full explanation is in Section 4.4.1 of the Haskell 2010 Report:




If a variable f is defined without providing a corresponding type signature declaration, then each use of f outside its own declaration group (see Section 4.5) is treated as having the corresponding inferred, or principal type. However, to ensure that type inference is still possible, the defining occurrence, and all uses of f within its declaration group must have the same monomorphic type (from which the principal type is obtained by generalization, as described in Section 4.5.2).




The same section later presents an example of polymorphic recursion supported by a type signature.



My understanding is that unaided type inference is generally undecidable in the presence of polymorphic recursion, so Haskell doesn't even try.



In this case, the type checker starts with



w :: a


where a is a meta-variable. Since fromInteger is called with w as an argument within its own declaration (and therefore within its declaration group), the type checker unifies a with Integer. There are no variables left to generalize.






share|improve this answer




















  • 1





    My bachelor was about a simple type inferencer for a subset of Haskell including typeclasses & polymorphic recursion. A very simple approach is to limit the depth of the polymorphic recursion up to k depth. Most useful cases of polymorphic recursion can be inferred with a very low depth bound (like k=1 or k=2). Anyway Haskell type inference is already undecidable so that's not the only reason why it's not allowed. An other reason is probably performance, it surely makes type inference O(k·f(n)) instead of O(f(n)) since you may need to do all over again for k times.

    – Bakuriu
    3 hours ago






  • 1





    @Bakuriu, I am pretty sure that Haskell 2010 without polymorphic recursion has full type inference--it's basically Hindley-Milner at that point, plus type classes and defaulting. Do you have a reference saying otherwise? As for some limited recursion depth: that sounds like a potentially useful extension, but it has a very different flavor from what the Haskell Report tends to do. I would find such a feature most useful for discovering the right type signatures for polymorphic recursive code.

    – dfeuer
    2 hours ago












  • Yes, but I think all extensions to the type systems on top of Haskell2010 make type inference undecidable. Note that for example Type families are "artificially" limited to avoid undecidable instances by forbidding certain well-formed programs by default, so allowing a "k-recursive" polymorphic recursion would not be very different from that case, IMHO.

    – Bakuriu
    1 hour 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%2f55402733%2fwhy-does-ghc-infer-a-monomorphic-type-here-even-with-monomorphismrestriction-di%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









13














Polymorphic recursion (where a function calls itself at a different type than the one at which it was called) always requires a type signature. The full explanation is in Section 4.4.1 of the Haskell 2010 Report:




If a variable f is defined without providing a corresponding type signature declaration, then each use of f outside its own declaration group (see Section 4.5) is treated as having the corresponding inferred, or principal type. However, to ensure that type inference is still possible, the defining occurrence, and all uses of f within its declaration group must have the same monomorphic type (from which the principal type is obtained by generalization, as described in Section 4.5.2).




The same section later presents an example of polymorphic recursion supported by a type signature.



My understanding is that unaided type inference is generally undecidable in the presence of polymorphic recursion, so Haskell doesn't even try.



In this case, the type checker starts with



w :: a


where a is a meta-variable. Since fromInteger is called with w as an argument within its own declaration (and therefore within its declaration group), the type checker unifies a with Integer. There are no variables left to generalize.






share|improve this answer




















  • 1





    My bachelor was about a simple type inferencer for a subset of Haskell including typeclasses & polymorphic recursion. A very simple approach is to limit the depth of the polymorphic recursion up to k depth. Most useful cases of polymorphic recursion can be inferred with a very low depth bound (like k=1 or k=2). Anyway Haskell type inference is already undecidable so that's not the only reason why it's not allowed. An other reason is probably performance, it surely makes type inference O(k·f(n)) instead of O(f(n)) since you may need to do all over again for k times.

    – Bakuriu
    3 hours ago






  • 1





    @Bakuriu, I am pretty sure that Haskell 2010 without polymorphic recursion has full type inference--it's basically Hindley-Milner at that point, plus type classes and defaulting. Do you have a reference saying otherwise? As for some limited recursion depth: that sounds like a potentially useful extension, but it has a very different flavor from what the Haskell Report tends to do. I would find such a feature most useful for discovering the right type signatures for polymorphic recursive code.

    – dfeuer
    2 hours ago












  • Yes, but I think all extensions to the type systems on top of Haskell2010 make type inference undecidable. Note that for example Type families are "artificially" limited to avoid undecidable instances by forbidding certain well-formed programs by default, so allowing a "k-recursive" polymorphic recursion would not be very different from that case, IMHO.

    – Bakuriu
    1 hour ago















13














Polymorphic recursion (where a function calls itself at a different type than the one at which it was called) always requires a type signature. The full explanation is in Section 4.4.1 of the Haskell 2010 Report:




If a variable f is defined without providing a corresponding type signature declaration, then each use of f outside its own declaration group (see Section 4.5) is treated as having the corresponding inferred, or principal type. However, to ensure that type inference is still possible, the defining occurrence, and all uses of f within its declaration group must have the same monomorphic type (from which the principal type is obtained by generalization, as described in Section 4.5.2).




The same section later presents an example of polymorphic recursion supported by a type signature.



My understanding is that unaided type inference is generally undecidable in the presence of polymorphic recursion, so Haskell doesn't even try.



In this case, the type checker starts with



w :: a


where a is a meta-variable. Since fromInteger is called with w as an argument within its own declaration (and therefore within its declaration group), the type checker unifies a with Integer. There are no variables left to generalize.






share|improve this answer




















  • 1





    My bachelor was about a simple type inferencer for a subset of Haskell including typeclasses & polymorphic recursion. A very simple approach is to limit the depth of the polymorphic recursion up to k depth. Most useful cases of polymorphic recursion can be inferred with a very low depth bound (like k=1 or k=2). Anyway Haskell type inference is already undecidable so that's not the only reason why it's not allowed. An other reason is probably performance, it surely makes type inference O(k·f(n)) instead of O(f(n)) since you may need to do all over again for k times.

    – Bakuriu
    3 hours ago






  • 1





    @Bakuriu, I am pretty sure that Haskell 2010 without polymorphic recursion has full type inference--it's basically Hindley-Milner at that point, plus type classes and defaulting. Do you have a reference saying otherwise? As for some limited recursion depth: that sounds like a potentially useful extension, but it has a very different flavor from what the Haskell Report tends to do. I would find such a feature most useful for discovering the right type signatures for polymorphic recursive code.

    – dfeuer
    2 hours ago












  • Yes, but I think all extensions to the type systems on top of Haskell2010 make type inference undecidable. Note that for example Type families are "artificially" limited to avoid undecidable instances by forbidding certain well-formed programs by default, so allowing a "k-recursive" polymorphic recursion would not be very different from that case, IMHO.

    – Bakuriu
    1 hour ago













13












13








13







Polymorphic recursion (where a function calls itself at a different type than the one at which it was called) always requires a type signature. The full explanation is in Section 4.4.1 of the Haskell 2010 Report:




If a variable f is defined without providing a corresponding type signature declaration, then each use of f outside its own declaration group (see Section 4.5) is treated as having the corresponding inferred, or principal type. However, to ensure that type inference is still possible, the defining occurrence, and all uses of f within its declaration group must have the same monomorphic type (from which the principal type is obtained by generalization, as described in Section 4.5.2).




The same section later presents an example of polymorphic recursion supported by a type signature.



My understanding is that unaided type inference is generally undecidable in the presence of polymorphic recursion, so Haskell doesn't even try.



In this case, the type checker starts with



w :: a


where a is a meta-variable. Since fromInteger is called with w as an argument within its own declaration (and therefore within its declaration group), the type checker unifies a with Integer. There are no variables left to generalize.






share|improve this answer















Polymorphic recursion (where a function calls itself at a different type than the one at which it was called) always requires a type signature. The full explanation is in Section 4.4.1 of the Haskell 2010 Report:




If a variable f is defined without providing a corresponding type signature declaration, then each use of f outside its own declaration group (see Section 4.5) is treated as having the corresponding inferred, or principal type. However, to ensure that type inference is still possible, the defining occurrence, and all uses of f within its declaration group must have the same monomorphic type (from which the principal type is obtained by generalization, as described in Section 4.5.2).




The same section later presents an example of polymorphic recursion supported by a type signature.



My understanding is that unaided type inference is generally undecidable in the presence of polymorphic recursion, so Haskell doesn't even try.



In this case, the type checker starts with



w :: a


where a is a meta-variable. Since fromInteger is called with w as an argument within its own declaration (and therefore within its declaration group), the type checker unifies a with Integer. There are no variables left to generalize.







share|improve this answer














share|improve this answer



share|improve this answer








edited 2 hours ago

























answered 4 hours ago









dfeuerdfeuer

33.5k349133




33.5k349133







  • 1





    My bachelor was about a simple type inferencer for a subset of Haskell including typeclasses & polymorphic recursion. A very simple approach is to limit the depth of the polymorphic recursion up to k depth. Most useful cases of polymorphic recursion can be inferred with a very low depth bound (like k=1 or k=2). Anyway Haskell type inference is already undecidable so that's not the only reason why it's not allowed. An other reason is probably performance, it surely makes type inference O(k·f(n)) instead of O(f(n)) since you may need to do all over again for k times.

    – Bakuriu
    3 hours ago






  • 1





    @Bakuriu, I am pretty sure that Haskell 2010 without polymorphic recursion has full type inference--it's basically Hindley-Milner at that point, plus type classes and defaulting. Do you have a reference saying otherwise? As for some limited recursion depth: that sounds like a potentially useful extension, but it has a very different flavor from what the Haskell Report tends to do. I would find such a feature most useful for discovering the right type signatures for polymorphic recursive code.

    – dfeuer
    2 hours ago












  • Yes, but I think all extensions to the type systems on top of Haskell2010 make type inference undecidable. Note that for example Type families are "artificially" limited to avoid undecidable instances by forbidding certain well-formed programs by default, so allowing a "k-recursive" polymorphic recursion would not be very different from that case, IMHO.

    – Bakuriu
    1 hour ago












  • 1





    My bachelor was about a simple type inferencer for a subset of Haskell including typeclasses & polymorphic recursion. A very simple approach is to limit the depth of the polymorphic recursion up to k depth. Most useful cases of polymorphic recursion can be inferred with a very low depth bound (like k=1 or k=2). Anyway Haskell type inference is already undecidable so that's not the only reason why it's not allowed. An other reason is probably performance, it surely makes type inference O(k·f(n)) instead of O(f(n)) since you may need to do all over again for k times.

    – Bakuriu
    3 hours ago






  • 1





    @Bakuriu, I am pretty sure that Haskell 2010 without polymorphic recursion has full type inference--it's basically Hindley-Milner at that point, plus type classes and defaulting. Do you have a reference saying otherwise? As for some limited recursion depth: that sounds like a potentially useful extension, but it has a very different flavor from what the Haskell Report tends to do. I would find such a feature most useful for discovering the right type signatures for polymorphic recursive code.

    – dfeuer
    2 hours ago












  • Yes, but I think all extensions to the type systems on top of Haskell2010 make type inference undecidable. Note that for example Type families are "artificially" limited to avoid undecidable instances by forbidding certain well-formed programs by default, so allowing a "k-recursive" polymorphic recursion would not be very different from that case, IMHO.

    – Bakuriu
    1 hour ago







1




1





My bachelor was about a simple type inferencer for a subset of Haskell including typeclasses & polymorphic recursion. A very simple approach is to limit the depth of the polymorphic recursion up to k depth. Most useful cases of polymorphic recursion can be inferred with a very low depth bound (like k=1 or k=2). Anyway Haskell type inference is already undecidable so that's not the only reason why it's not allowed. An other reason is probably performance, it surely makes type inference O(k·f(n)) instead of O(f(n)) since you may need to do all over again for k times.

– Bakuriu
3 hours ago





My bachelor was about a simple type inferencer for a subset of Haskell including typeclasses & polymorphic recursion. A very simple approach is to limit the depth of the polymorphic recursion up to k depth. Most useful cases of polymorphic recursion can be inferred with a very low depth bound (like k=1 or k=2). Anyway Haskell type inference is already undecidable so that's not the only reason why it's not allowed. An other reason is probably performance, it surely makes type inference O(k·f(n)) instead of O(f(n)) since you may need to do all over again for k times.

– Bakuriu
3 hours ago




1




1





@Bakuriu, I am pretty sure that Haskell 2010 without polymorphic recursion has full type inference--it's basically Hindley-Milner at that point, plus type classes and defaulting. Do you have a reference saying otherwise? As for some limited recursion depth: that sounds like a potentially useful extension, but it has a very different flavor from what the Haskell Report tends to do. I would find such a feature most useful for discovering the right type signatures for polymorphic recursive code.

– dfeuer
2 hours ago






@Bakuriu, I am pretty sure that Haskell 2010 without polymorphic recursion has full type inference--it's basically Hindley-Milner at that point, plus type classes and defaulting. Do you have a reference saying otherwise? As for some limited recursion depth: that sounds like a potentially useful extension, but it has a very different flavor from what the Haskell Report tends to do. I would find such a feature most useful for discovering the right type signatures for polymorphic recursive code.

– dfeuer
2 hours ago














Yes, but I think all extensions to the type systems on top of Haskell2010 make type inference undecidable. Note that for example Type families are "artificially" limited to avoid undecidable instances by forbidding certain well-formed programs by default, so allowing a "k-recursive" polymorphic recursion would not be very different from that case, IMHO.

– Bakuriu
1 hour ago





Yes, but I think all extensions to the type systems on top of Haskell2010 make type inference undecidable. Note that for example Type families are "artificially" limited to avoid undecidable instances by forbidding certain well-formed programs by default, so allowing a "k-recursive" polymorphic recursion would not be very different from that case, IMHO.

– Bakuriu
1 hour 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%2f55402733%2fwhy-does-ghc-infer-a-monomorphic-type-here-even-with-monomorphismrestriction-di%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

Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

На ростанях Змест Гісторыя напісання | Месца дзеяння | Час дзеяння | Назва | Праблематыка трылогіі | Аўтабіяграфічнасць | Трылогія ў тэатры і кіно | Пераклады | У культуры | Зноскі Літаратура | Спасылкі | НавігацыяДагледжаная версіяправерана1 зменаДагледжаная версіяправерана1 зменаАкадэмік МІЦКЕВІЧ Канстанцін Міхайлавіч (Якуб Колас) Прадмова М. І. Мушынскага, доктара філалагічных навук, члена-карэспандэнта Нацыянальнай акадэміі навук Рэспублікі Беларусь, прафесараНашаніўцы ў трылогіі Якуба Коласа «На ростанях»: вобразы і прататыпы125 лет Янке МавруКнижно-документальная выставка к 125-летию со дня рождения Якуба Коласа (1882—1956)Колас Якуб. Новая зямля (паэма), На ростанях (трылогія). Сулкоўскі Уладзімір. Радзіма Якуба Коласа (серыял жывапісных палотнаў)Вокладка кнігіІлюстрацыя М. С. БасалыгіНа ростаняхАўдыёверсія трылогііВ. Жолтак У Люсiнскай школе 1959

Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп