[Haskell-cafe] Re: let vs. where

ChrisK haskell at list.mightyreason.com
Tue Nov 13 19:05:01 EST 2007


Dan Piponi wrote:
> On Nov 13, 2007 1:24 PM, Ryan Ingram <ryani.spam at gmail.com> wrote:
>> I tend to prefer where, but I think that guards & function declarations are
>> more readable than giant if-thens and case constructs.
> 
> Up until yesterday I had presumed that guards only applied to
> functions. But I was poking about in the Random module and discovered
> that you can write things like
> 
> a | x > 1 = 1
>   | x < -1 = -1
>   | otherwise = x
> 
> where 'a' clearly isn't a function. Seems like a nice readable format
> to use. Probably everyone except me already knew this already though.
> --
> Dan

I recalled having used this trick in the regex-tdfa regular expression matching
engine.  There is an option for single-line vs multi-line matching that changes
whether ^ and $ get tested against '\n'.  By using this trick I was able to
decide which matching to use once and that decision gets cached:

> matchHere regexIn offsetIn prevIn inputIn = ans where
>   ans = if subCapture then runHerePure else noCap
>     where subCapture = captureGroups (regex_execOptions regexIn)
>                     && (1<=rangeSize (bounds (regex_groups regexIn)))
>
> [...snip...]
>
>   -- Select which style of ^ $ tests are performed.
>   test | multiline (regex_compOptions regexIn) = test_multiline
>        | otherwise = test_singleline
>     where test_multiline Test_BOL _off prev _input = prev == '\n'
>           test_multiline Test_EOL _off _prev input = case input of
>                                                        [] -> True
>                                                        (next:_) -> next == '\n'
>           test_singleline Test_BOL off _prev _input = off == 0
>           test_singleline Test_EOL _off _prev input = null input

-- 
Chris



More information about the Haskell-Cafe mailing list