[Haskell-cafe] Random numbers / monads - beginner question

Dan Weston westondan at imageworks.com
Thu May 8 14:52:50 EDT 2008


Henning Thielemann wrote:
> 
> On Thu, 8 May 2008, Madoc wrote:
> 
>> minValue = 0::Int
>> maxValue = 1000::Int
>>
>> normalize a | a < minValue = minValue
>>            | a > maxValue = maxValue
>>            | otherwise = a
> 
> 
> normalize' = min maxValue . max minValue

There is a curiosity here. The functions normalize and normalize' are 
extensionally equal only because minValue <= maxValue, but intensionally 
different. The intensional equivalent is to reverse order of composition:

normalize'' = max minValue . min maxValue

which remains equal to to normalize whatever the values of minValue and 
maxValue.

That the order of composition (or of guarded expressions) matters 
conditionally base on its parameters is reason enough for the original 
poster to decide what the "right answer" should be if maxValue < 
minValue. These corner cases are often where future bugs lie dormant. My 
choice would be:

normalize'''    = max trueMin . min trueMax
   where trueMin = min minValue maxValue
         trueMax = max minValue maxValue

Now the function makes no assumptions about external values. This is no 
less efficient than before, since trueMin and trueMax are CAFs evaluated 
only once.




More information about the Haskell-Cafe mailing list