Note that there are some explanatory texts on larger screens.

plurals
  1. POData types and non exhaustive patterns
    primarykey
    data
    text
    <p>If have a data type </p> <pre><code>data Arith = Con Int | Add Arith Arith | Sub Arith Arith | Mul Arith Arith | Div Arith Arith </code></pre> <p>an instance: </p> <pre><code>instance Show Arith where show (Con i) = show i show (Add e1 e2) = "(" ++ show e1 ++ " + " ++ show e2 ++ ")" show (Sub e1 e2) = "(" ++ show e1 ++ " - " ++ show e2 ++ ")" show (Mul e1 e2) = "(" ++ show e1 ++ " * " ++ show e2 ++ ")" show (Div e1 e2) = "(" ++ show e1 ++ " / " ++ show e2 ++ ")" </code></pre> <p>and a function evaluate which is expected behave like:</p> <pre><code>ghci&gt; eval (Mul (Con 5) (Div (Con 6) (Con 2) )) 15 </code></pre> <p>this is what I've come up with that's not working when I try anything more complex then the basic case. </p> <pre><code>eval :: ArithExp -&gt; Int eval (Con e1) = e1 eval (Add (Con e1) (Con e2)) = e1 + e2 eval (Sub (Con e1) (Con e2)) = e1 - e2 eval (Div (Con e1) (Con e2)) = e1 `div` e2 eval (Mul (Con e1) (Con e2)) = e1 * e2 </code></pre> <p>When I try anything that isn't in this case, of course I get an error about exhaustive patterns. </p> <p>So my question is, how do I catch all of the patterns without doing it the naive way?</p> <p>I did notice that Add is defined as Add Arith Arith, Sub Arith Arith so how would I take advantage of that in my eval function? I tried doing:</p> <pre><code>eval (Add Arith Arith) = Arith + Arith </code></pre> <p>But that didn't work either, (not in scope error). </p> <p>You don't need to give me a full working code example or anything, I'm just trying to get pointed in the right direction. Still new at haskell. </p> <p>Thanks. </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.
    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