Note that there are some explanatory texts on larger screens.

plurals
  1. PO"Overloaded" value constructors
    text
    copied!<p>In <a href="http://learnyouahaskell.com/making-our-own-types-and-typeclasses" rel="nofollow">"Making Our Own Types and Typeclasses"</a> they give the following piece of code : </p> <pre><code>data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) surface :: Shape -&gt; Float surface (Circle _ r) = pi * r ^ 2 surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1) nudge :: Shape -&gt; Float -&gt; Float -&gt; Shape nudge (Circle (Point x y) r) a b = Circle (Point (x+a) (y+b)) r nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b = Rectangle (Point (x1+a) (y1+b)) (Point (x2+a) (y2+b)) main = do print (surface (Circle (Point 0 0) 24)) print (nudge (Circle (Point 34 34) 10) 5 10) </code></pre> <p>As it stands the pattern matching against constructors is getting quite cluttered at the point </p> <pre><code>nudge (Rectangle (Point x1 y1) (Point x2 y2)) a b = .... </code></pre> <p>Had we defined the Shape type as : </p> <pre><code>data Shape = Circle Point Float | Rectangle Float Float Float Float deriving (Show) </code></pre> <p>Then even though we lose a bit of clarity into the nature of the type, the patten matching looks less cluttered, as can be seen below : </p> <pre><code>data Point = Point Float Float deriving (Show) data Shape = Circle Point Float | Rectangle Float Float Float Float deriving (Show) surface :: Shape -&gt; Float surface (Circle _ r) = pi * r ^ 2 surface (Rectangle x1 y1 x2 y2) = (abs $ x2 - x1) * (abs $ y2 - y1) nudge :: Shape -&gt; Float -&gt; Float -&gt; Shape nudge (Circle (Point x y) r) a b = Circle (Point (x+a) (y+b)) r nudge (Rectangle x1 y1 x2 y2) a b = Rectangle (x1+a) (y1+b) (x2+a) (y2+b) main = do print (surface (Circle (Point 0 0) 24)) print (nudge (Circle (Point 34 34) 10) 5 10) </code></pre> <p>My question is whether it is possible to have both </p> <pre><code>Rectangle Point Point </code></pre> <p>and </p> <pre><code>Rectangle Float Float Float Float </code></pre> <p>in the same piece of code (i.e. a sort of "overloading" of value constructors), so that we can do something like : </p> <pre><code>... surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1) ... nudge (Rectangle x1 y1 x2 y2) a b = Rectangle (x1+a) (y1+b) (x2+a) (y2+b) </code></pre> <p>where the "..." denotes the same as in the code above. Also are there any other tricks to make the notation a bit more compact at the "nudge (Rectangle...." point? Thanks</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