Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not completely sure what examples would count for you, because you mention both non-locality and mutual recursion, and I don't understand whether an example that exhibits just non-locality is enough.</p> <p>I will say that a common technique in Haskell is to write functions whose return type is a class-constrained type variable not mentioned in the argument types. For example, like this:</p> <pre class="lang-hs prettyprint-override"><code>foo :: (Result a) =&gt; String -&gt; a foo = toResult . transform -- transform :: String -&gt; String class Result a where toResult :: String -&gt; a -- Example implementation of Result class—with this, callers that -- expect foo to return an Integer will get the length of the result -- of transform. instance Result Integer where toResult = length </code></pre> <p>In this case, the concrete type of the result of any call to <code>foo</code> is determined by type inference at the calling site. I.e., the return type of any call to <code>foo</code> is inferred from information not present in the definition of <code>foo</code>.</p> <p>One practical example of this is Haskell's regular expression libraries. The interface uses this pattern so that, instead of having a bunch of different regexp matching functions that return different types, there is a regexp matching operator that is polymorphic on the return type as shown above, and thus the caller's type inference controls what is returned.</p> <p>So for example, if you do regexp matching in a calling context where the inferred return type is an integer, you get back number of matches. If the calling context expects a boolean, you get True if there were any matches. If the calling context expects a list of strings, you get a list of the substrings that matched the regexp. A bunch of other return type-specific behaviors are defined—and you can define your own for arbitrary return types by implementing your own instances of the library's type class for results.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload