Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy should I use case expressions if I can use "equations"?
    primarykey
    data
    text
    <p>I'm learning Haskell, from the book "Real World Haskell". In pages 66 and 67, they show the case expressions with this example:</p> <pre><code>fromMaybe defval wrapped = case wrapped of Nothing -&gt; defval Just value -&gt; value </code></pre> <p>I remember a similar thing in F#, but (as shown earlier in the book) Haskell can define functions as series of equations; while AFAIK, F Sharp cannot. So I tried to define this in such a way:</p> <pre><code>fromMaybe2 defval Nothing = defval fromMaybe2 defval (Just value) = value </code></pre> <p>I loaded it in GHCi and after a couple of results, I convinced myself it was the same However; this makes me wonder, why should there be case expressions when equations:</p> <ul> <li>are more comprehensible (it's Mathematics; why use <code>case something of</code>, who says that?);</li> <li>are less verbose (2 vs 4 lines);</li> <li>require much less structuring and syntatic sugar (<code>-&gt;</code> could be an operator, look what they've done!);</li> <li>only use variables when needed (in basic cases, such as this <code>wrapped</code> just takes up space).</li> </ul> <p>What's good about case expressions? Do they exist only because similar FP-based languages (such as F#) have them? Am I missing something?</p> <h1>Edit:</h1> <p>I see from @freyrs's answer that the compiler makes these exactly the same. So, equations can always be turned into case expressions (as expected). My next question is the converse; can one go the opposite route of the compiler and use equations with <code>let</code>/<code>where</code> expressions to express any case expression?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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