Algebraic types, shared parameters, pattern matching

I noticed that with algebraic types I can do something like so: code -------- data Projectile = Bullet { range :: Double } | Missile { range :: Double } | Torpedo { range :: Double } f p = let r = range p in ...whatever... -------- (This is interesting in and of itself, as I don't in this case have to do pattern matching for each constructor. Also, apparently not all the constructors actually need to have a "range" selector for the program to compile!) However, what if I wanted to make the same function f (again, without multiple lines of pattern matching) but using a "simpler" data type like so: code: -------- type Range = Double data Projectile = Bullet Range | Missile Range | Torpedo Range -------- My first try was code -------- f (_ r) = ... -------- But that doesn't work. -- frigidcode.com indicium.us

On Wed, Oct 31, 2012 at 7:36 PM, Christopher Howard
(This is interesting in and of itself, as I don't in this case have to do pattern matching for each constructor. Also, apparently not all the constructors actually need to have a "range" selector for the program to compile!)
I would avoid using this "feature" of the language, because non-total functions are a hassle.
code: -------- type Range = Double
data Projectile = Bullet Range | Missile Range | Torpedo Range
f (_ r) = ... --------
Nope, you can't do that. But you can do this: data ProjectileType = Bullet | Missile | Torpedo data Projectile = Projectile ProjectileType Range f (Projectile _ r) = ... -Karl
participants (2)
-
Christopher Howard
-
Karl Voelker