[Haskell-cafe] Constructors on left and right hand sides of equation

Richard A. O'Keefe ok at cs.otago.ac.nz
Thu Sep 18 02:08:52 UTC 2014


On 18/09/2014, at 2:03 AM, PATRICK BROWNE wrote:

> Dear list
> In Eq 1 is  (NewGlass i) on the LHS distinct from (NewGlass i) on the RHS?
> In Eq2  are the occurrences  of the data constructor Fill on the LHS and RHS distinct?
> 
> data Glass = NewGlass Int | Fill Glass Int deriving Show
> drink :: Glass -> Int -> Glass
> drink (NewGlass i) j = (NewGlass i)   -- Eq 1
> drink (Fill m i) j
>                | full (Fill m i)  = Fill (NewGlass (size m))  ((size m) - j)  -- Eq 2
>                | (i >= j) = Fill m  (i-j)
>                | otherwise = drink m (j-1)

The question question is "what do you MEAN by 'are they distinct'"?

They are two distinct references to a single binding occurrence
of an identifier.  In Eq1, the first occurrence is in a pattern,
and the second is in an expression.

I wonder if you were interested in the question whether
the second occurrence of NewGlass i would allocate new storage
or whether it would use whatever the first occurrence matched?
In that case, I believe the answer is "it's up to the compiler".
You can *ask* for the matched data to be shared:

drink g@(NewGlass _) _ = g
drink g@(Fill m i  ) j
  | full g = Fill (NewGlass (size m)) (size m - j)
  | i >= j = Fill m (i - j)
  | True   = drink m (j - 1)

Someone else has already pointed out

data Proxy a = Proxy

-- foo :: Proxy a -> Proxy b
foo Proxy = Proxy  -- Eq3

where the two occurrences of Proxy in Eq3 can have different types.
But note that

-- bar :: Proxy a -> Proxy a
bar p at Proxy = p  -- Eq4

The two occurrences of the variable p in Eq4 must have
the same type (and the same value).



More information about the Haskell-Cafe mailing list