[Haskell-beginners] Pattern guard inside function

Bob Hutchison hutch-lists at recursive.ca
Tue Nov 6 13:41:33 CET 2012

On 2012-10-31, at 1:22 PM, Bob Hutchison <hutch-lists at recursive.ca> wrote:

> Hi,
>
> On 2012-10-31, at 10:02 AM, Nathan Hüsken <nathan.huesken at posteo.de> wrote:
>
>> Hey
>>
>> I have a function which originaly locked like this:
>>
>> collInfo :: Rect -> Rect -> Maybe CollInfo
>> collInfo (Rect x1 y1 w1 h1) (Rect x2 y2 w2 h2)
>> | x1 + w1 < x2 = Nothing
>> | x1 > x2 + w2 = Nothing
>> | y1 + h1 < y2 = Nothing
>> | y1 > y2 + h2 = Nothing
>> | otherwiese = Just \$ makeCollInfo r1 r2
>>
>> Now I want to refactor it to take Maybe input values
>>
>> collInfo' :: Maybe Rect -> Maybe Rect -> Maybe CollInfo
>> collInfo' mr1 mr2 =
>> r1 <- mr1
>> r2 <- mr2
>> collInfo r1 r2
>>
>> This is fine, but I would like to write it using only one function. Is
>> there any possibility I can remove collInfo and merge its body into
>> collInfo' and still somehow use the guards (and not a bunch of ifs)?
>
> maybe like:
>
> collInfo'' :: Maybe Rect -> Maybe Rect -> Maybe CollInfo
> collInfo'' (Just r1@(Rect x1 y1 w1 h1)) (Just r2@(Rect x2 y2 w2 h2))
>  | x1 + w1 < x2 = Nothing
>  | x1 > x2 + w2 = Nothing
>  | y1 + h1 < y2 = Nothing
>  | y1 > y2 + h2 = Nothing
>  | otherwise = Just \$ makeCollInfo r1 r2
> collInfo'' _ _ = Nothing

Here's another variation using Maybe as an applicative functor:

collInfo''' :: Maybe Rect -> Maybe Rect -> Maybe CollInfo
collInfo''' r1 r2 = join \$ collInfo <\$> r1 <*> r2

The join is in there to get rid a Maybe in (Maybe (Maybe _)). There's probably a way to avoid that but I don't know what it is… I'm learning this stuff myself.

Cheers,
Bob