[Haskell-cafe] How can i safely change the value of specified key ?

Bulat Ziganshin bulat.ziganshin at gmail.com
Thu Oct 22 05:23:42 EDT 2009

Hello zaxis,

Thursday, October 22, 2009, 1:03:21 PM, you wrote:

>>>value <- readIORef aaa
>>>writeIORef aaa (f value) 
> then aaa will *point to* a new value. The original value will be Garbage
> Collected, right ?

yes, exactly

> BTW, 
> Is [(1,1),(2,2),(3,3)] been regarded as a hash ? If not, what is the best
> way to change it to [(1,1),(2,2222),(3,3)] in function `f` ?

hm, i'm frequently use lists of tuples as dictionaries, there is
Data.List.lookup function that perfroms lookup. but these are stored
naively so it's useful only for small dictionaries. if you need hash,
you can use Data.Hashtable module (it provides hash with imperative
access), or use Data.Map that has pure interface. again, for the first
time i strongly recommend to learn Data.Map. if you will learn Haskell
as imperative language, you will find it slow, awkward and useless. if
you will learn functional features and only then go to imperative
part, you may find it much more pleasant

just one example from my code:

  repeat_while (receiveP pipe) notTheEnd $ \(FileStart fi) -> do
    extract_file command fi $ \writer -> do
      repeat_while (receiveP pipe) notDataEnd (\(DataChunk buf len) -> do writer buf len; send_backP pipe (buf,len))

yes, it's imperative but it includes several lambdas per each line

> Bulat Ziganshin-2 wrote:
>> Hello zaxis,
>> Thursday, October 22, 2009, 11:28:14 AM, you wrote:
>>> aaa <- newIORef ([]::[(Int,Int)])
>>> writeIORef aaa [(1,1),(2,2),(3,3)] 
>>> then if i want to change aaa to [(1,1),(2,222),(3,3)] , what's the best
>>> way
>>> ? 
>>> re-write aaa is not permitted.
>> it's the only way. in Haskell, you have *immutable* values. aaa is a
>> reference to immutable value. you can mutate reference so it will
>> point to another immutable value but you cannot change this value.
>> there are two ways to make aaa==[(1,1),(2,222),(3,3)]. first, you can
>> apply function to whole value:
>> value <- readIORef aaa
>> writeIORef aaa (f value)
>> second, you may create list of IORefs, tuple of IORefs and so:
>> a <- newIORef (1,1)
>> ...
>> let aaa = [a,b,c]
>> now aaa is a immutable list of mutable IORefs. of course, you can
>> create IORef pointing to list of IORefs too
>> -- 
>> Best regards,
>>  Bulat                            mailto:Bulat.Ziganshin at gmail.com
>> _______________________________________________
>> Haskell-Cafe mailing list
>> Haskell-Cafe at haskell.org
>> http://www.haskell.org/mailman/listinfo/haskell-cafe

Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com

More information about the Haskell-Cafe mailing list