[Haskell-cafe] Can I destructive rebind a local variable in haskell?

Evan Laforge qdunkan at gmail.com
Tue Jan 6 03:00:52 EST 2009


2009/1/6 Luke Palmer <lrpalmer at gmail.com>:
> 2009/1/6 Wang, Chunye (NSN - CN/Beijing) <chunye.wang at nsn.com>
> Dear haskeller,
>>
>>
>>     Can I destructive rebind a local variable like this
>>
>> import System.Directory
>> test filename = do
>>   is_dir <- doesDirectoryExist filename
>>   let filename = if not is_dir then filename else filename
>
> Nope.  The "filename" on the right side of the = is the same as the
> "filename" on the left, so you're making an infinite loop, the same way:
>    let x = x in x
> is an infinite loop.  However you can make a new name as you are trying, you
> just can't reference the old one.  e.g.:
>    let filename = 42

You can also reuse the name exactly by using bind+return instead of let:
test filename = do
   is_dir <- doesDirectoryExist filename
   filename <- return $ if not is_dir then filename else filename

I'm not a huge fan of the prime thing because it's tiny and easy to
miss and if you forget it you probably won't get a type error, you'll
just get a bug, possibly a subtle one.  Besides, what's the next step?
 filename''?  filename'''?


More information about the Haskell-Cafe mailing list