2

Given:

λ: >let m = newMVar "foo"

λ: >m >>= readMVar 
"foo"

I tried to use modifyMVar_:

λ: >:t modifyMVar_
modifyMVar_ :: MVar a -> (a -> IO a) -> IO ()

through:

λ: >m >>= \mvar -> modifyMVar_ mvar (\_ -> return "bar")

But, it doesn't look like it modified m from "foo" to "bar".

λ: >m >>= readMVar 
"foo"

What'd I do wrong?

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
  • Shouldn't you write it all in one line? `m >>= \mvar -> modifyMVar_ mvar (\_ -> return "bar") >> readMVar`? – Willem Van Onsem Oct 28 '17 at 19:07
  • 2
    I'd recommend you read about [`let` vs `<-`](https://stackoverflow.com/questions/28624408/equal-vs-left-arrow-symbols-in-haskell). Above you used `let` when you meant `<-`, I think. – chi Oct 28 '17 at 19:58
  • Possible duplicate of [Setting off a interval on application launch in a Haskell Servant app](https://stackoverflow.com/questions/46959753/setting-off-a-interval-on-application-launch-in-a-haskell-servant-app) – jberryman Oct 28 '17 at 20:06
  • @jberryman that question's code is so much more involved though. here it is simple, short. also, the setting and specific types are different. – Will Ness Oct 28 '17 at 20:13

1 Answers1

9

m creates new MVar with "foo" every time it's called. You're modifying one MVar then making a new one and checking that. It is the same problem as seen here Setting off a interval on application launch in a Haskell Servant app with exception that there it was an IORef.

myVar <- m
modifyMVar_ myVar (\_ -> return "bar")
readMVar myVar

This should give you "bar" as expected.

Mateusz Kowalczyk
  • 2,036
  • 1
  • 15
  • 29