Send Beginners mailing list submissions to
        [email protected]

To subscribe or unsubscribe via the World Wide Web, visit
        http://www.haskell.org/mailman/listinfo/beginners
or, via email, send a message with subject or body 'help' to
        [email protected]

You can reach the person managing the list at
        [email protected]

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Beginners digest..."


Today's Topics:

   1.  Global variable question (Joe Van Dyk)
   2. Re:  Global variable question (Brent Yorgey)
   3. Re:  Global variable question (Edward Z. Yang)
   4. Re:  Interrupting a thread (Dean Herington)
   5. Re:  Interrupting a thread (Floptical Logic)
   6. Re:  Interrupting a thread (Chadda? Fouch?)
   7.  Data.Map, types and debug (legajid)


----------------------------------------------------------------------

Message: 1
Date: Wed, 30 Dec 2009 17:49:12 -0800
From: Joe Van Dyk <[email protected]>
Subject: [Haskell-beginners] Global variable question
To: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

What's the appropriate way to write this in Haskell?

# Ruby code, ignore the thread-unsafety for now.
class Ticker
  @@tick = 0
  def self.update!
    @@tick += 1
  end
  def self.current
    return @@tick
   end
end

Ticker.update! # 1
Ticker.update! # 2
Ticker.current  # 2


-- 
Joe Van Dyk
http://fixieconsulting.com


------------------------------

Message: 2
Date: Wed, 30 Dec 2009 20:59:52 -0500
From: Brent Yorgey <[email protected]>
Subject: Re: [Haskell-beginners] Global variable question
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii

On Wed, Dec 30, 2009 at 05:49:12PM -0800, Joe Van Dyk wrote:
> What's the appropriate way to write this in Haskell?
> 
> # Ruby code, ignore the thread-unsafety for now.
> class Ticker
>   @@tick = 0
>   def self.update!
>     @@tick += 1
>   end
>   def self.current
>     return @@tick
>    end
> end
> 
> Ticker.update! # 1
> Ticker.update! # 2
> Ticker.current  # 2

If you really want a global ticker, use the State monad:

  tick :: State Int ()
  tick = modify (+1)

  -- increment the counter twice then return its new value
  mainStuff :: State Int Int
  mainStuff = tick >> tick >> get

-Brent


------------------------------

Message: 3
Date: Wed, 30 Dec 2009 21:05:34 -0500
From: "Edward Z. Yang" <[email protected]>
Subject: Re: [Haskell-beginners] Global variable question
To: Joe Van Dyk <[email protected]>
Cc: beginners <[email protected]>
Message-ID: <1262224821-sup-6...@ezyang>
Content-Type: text/plain; charset=UTF-8

Excerpts from Joe Van Dyk's message of Wed Dec 30 20:49:12 -0500 2009:
> What's the appropriate way to write this in Haskell?

Hi Joe,

The Ticker class is an example of stateful computation, which we try
to avoid in Haskell.  What are you really trying to do?

* If you a number, and you want to add to it, (+1) works
  plenty well.

* If you are going to be making ticks, but you don't care about
  reading the ticks until the end of the computation, the Writer monad
  is of interest.

* If you need to update the tick count and read it, the State
  monad is a good bet.

* If you're interested in curiosities from imperative land, STRef, IORef and
  other similar creatures may be helpful.

Cheers,
Edward


------------------------------

Message: 4
Date: Thu, 31 Dec 2009 02:21:02 -0500
From: Dean Herington <[email protected]>
Subject: Re: [Haskell-beginners] Interrupting a thread
To: Floptical Logic <[email protected]>,  "Stephen Blackheath [to
        Haskell-Beginners]"
        <[email protected]>
Cc: [email protected]
Message-ID: <a06240800c761feb96...@[192.168.1.102]>
Content-Type: text/plain; charset="us-ascii" ; format="flowed"

At 6:08 PM -0600 12/30/09, Floptical Logic wrote:
>On Sun, Dec 27, 2009 at 1:47 PM, Stephen Blackheath [to
>Haskell-Beginners] <[email protected]>
>wrote:
>>  MVars are the lowest-level operation for this kind of thing in Haskell,
>>  and they're very fast. Anything can be done with MVars but in some cases
>>  you need extra worker threads (cheap in Haskell), and you may even need
>>  to kill threads (which is a safe operation in Haskell).  CHP is higher
>>  level and designed for this sort of complexity, so you might want to
>>  look at that.  I'll give you the answer I know, which is a low-level
>>  MVar answer.
>>
>>  I have *not* tried compiling this code.
>>
>>
>>  import Control.Concurrent
>>  import Control.Concurrent.MVar
>>  import Data.Int
>>  import System.Time
>>
>>  type Microseconds = Int64
>>
>>  getSystemTime :: IO Microseconds
>>  getSystemTime = do
>>     (TOD sec pico) <- getClockTime
>>     return $!
>>         (fromIntegral sec::Int64) * 1000000 +
>>         (fromIntegral pico::Int64) `div` 1000000
>>
>>  type Stack a = [a]  -- or whatever type you want
>>
>>  isEmpty :: Stack a -> Bool
>>  isEmpty [] = True
>>  isEmpty _ = False
>>
>>  pop :: Stack a -> (a, Stack a)
>>
>>  data ScheduleInput = ModifyStack (Stack -> Stack) | WaitFor Microseconds
>>  | Timeout
>>
>>  never = maxBound :: Microseconds
>>
>>  schedule :: MVar ScheduleInput -> MVar a -> Stack a -> IO ()
>>  schedule inpVar wnVar stack = schedule_ never stack
>>   where
>>     schedule_ :: Microseconds -> Stack -> IO ()
>>     schedule_ timeout stack = do
>>         now <- getSystemTime
>>         let tillTimeout = 0 `max` (timeout - now)
>>         if tillTimeout == 0 && not (isEmpty stack) then do
>>             let (val, stack') = pop stack
>>             putMVar wnVar (PopValue val)
>>             schedule never stack'
>>           else do
>>             inp <- takeMVarWithTimeout (fromIntegral tillTimeout) inpVar
>>             case inp of
>>                 ModifyStack f -> schedule_ timeout (f stack)
>>                 WaitFor t        -> do
>>                     now <- getSystemTime
>>                     schedule (t+now) stack
>>                 Timeout        -> schedule timeout stack
>>
>>  readMVarWithTimeout :: Int -> MVar ScheduleInput -> IO ScheduleInput
>>  readMVar timeoutUS inpVar = do
>>     tid <- forkIO $ do
>>         threadDelay timeoutUS
>>         putMVar inpVar Timeout
>>     inp <- takeMVar inpVar
>>     killThread tid
>>     return inp
>>
>>  waitNotify :: MVar ScheduleInput -> MVar Int -> IO ()
>>  waitNotify schInp wnInp = do
>>     val <- takeMVar wnInp
>>     ...notify...
>>     let t = ....
>>     putMVar schInp $ WaitFor t  -- block input for the specified period
>>
>>  main = do
>>     schVar <- newEmptyMVar
>>     wnVar <- newEmptyMVar
>>     forkIO $ schedule schVar wnVar []
>>     forkIO $ waitNotify wnVar schVar
>>     ...
>>     -- Modify stack according to user input inside your main IO loop
>>     putMVar schVar $ ModifyStack $ \stack -> ...
>>
>>
>>  I'm sure this is not exactly what you want, but at least it illustrates
>>  how you can achieve anything you like by using MVars + extra worker
>>  threads + killing threads (useful for implementing timeouts).
>>
>>
>>  Steve
>>
>>  Floptical Logic wrote:
>>>  Hi,
>>>
>>>  I am new to concurrency in Haskell and I am having trouble
>>>  implementing the notion of interrupting a thread.
>>>
>>>  In a new thread, call it waitNotify, I am trying to do the following:
>>>  pop a number from a stack, wait some number of seconds based on the
>>>  number popped from the stack, perform some notification, and repeat
>>>  until there are no more numbers in the stack at which point we wait
>>>  for a new number.
>>>
>>>  These numbers will be supplied interactively by the user from main.
>>>  When the user supplies a new number, I want to interrupt whatever
>>>  waiting is happening in waitNotify, insert the number in the proper
>  >> position in the current stack, and resume waitNotify using the updated
>>>  stack.  Note, here "stack" is just a generalization; it will likely
>>>  just be a list.
>>>
>>>  What is the most idiomatic way to capture this sort of behavior in
>>>  Haskell?  My two challenges are the notion of interrupting a thread,
>>>  and sharing and updating this stack between threads (main and
>>>  waitNotify).
>>>
>>>  Thank you
>>>  _______________________________________________
>>>  Beginners mailing list
>>>  [email protected]
>>>  http://www.haskell.org/mailman/listinfo/beginners
>>>
>>  _______________________________________________
>>  Beginners mailing list
>>  [email protected]
>>  http://www.haskell.org/mailman/listinfo/beginners
>>
>
>Thanks Stephen.  That worked and things are starting to make more
>sense.  The crux of it all was the readMVarWithTimeout function which
>does exactly what I want.
>
>Now I want to extend this a bit further to use StateT.  I've modified
>the schedule function quite a bit, and now it has type schedule ::
>StateT MyState IO.  I keep the MVar actVar in MyState as well the list
>(stack) of wait times.  However, the type of forkIO is forkIO :: IO ()
>-> IO ThreadId.  How do I fork a new thread for schedule even though
>it is wrapped in the State monad?
>
>Thanks again.

You'll want something like this:

myFork :: StateT MyState IO () -> MyState -> StateT MyState IO ThreadId
myFork action initialState = liftIO (forkIO (evalStateT action initialState))

Dean


------------------------------

Message: 5
Date: Thu, 31 Dec 2009 02:21:33 -0600
From: Floptical Logic <[email protected]>
Subject: Re: [Haskell-beginners] Interrupting a thread
To: Dean Herington <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

On Thu, Dec 31, 2009 at 1:21 AM, Dean Herington
<[email protected]> wrote:
> At 6:08 PM -0600 12/30/09, Floptical Logic wrote:
>>
>> On Sun, Dec 27, 2009 at 1:47 PM, Stephen Blackheath [to
>> Haskell-Beginners] <[email protected]>
>> wrote:
>>>
>>>  MVars are the lowest-level operation for this kind of thing in Haskell,
>>>  and they're very fast. Anything can be done with MVars but in some cases
>>>  you need extra worker threads (cheap in Haskell), and you may even need
>>>  to kill threads (which is a safe operation in Haskell).  CHP is higher
>>>  level and designed for this sort of complexity, so you might want to
>>>  look at that.  I'll give you the answer I know, which is a low-level
>>>  MVar answer.
>>>
>>>  I have *not* tried compiling this code.
>>>
>>>
>>>  import Control.Concurrent
>>>  import Control.Concurrent.MVar
>>>  import Data.Int
>>>  import System.Time
>>>
>>>  type Microseconds = Int64
>>>
>>>  getSystemTime :: IO Microseconds
>>>  getSystemTime = do
>>>    (TOD sec pico) <- getClockTime
>>>    return $!
>>>        (fromIntegral sec::Int64) * 1000000 +
>>>        (fromIntegral pico::Int64) `div` 1000000
>>>
>>>  type Stack a = [a]  -- or whatever type you want
>>>
>>>  isEmpty :: Stack a -> Bool
>>>  isEmpty [] = True
>>>  isEmpty _ = False
>>>
>>>  pop :: Stack a -> (a, Stack a)
>>>
>>>  data ScheduleInput = ModifyStack (Stack -> Stack) | WaitFor Microseconds
>>>  | Timeout
>>>
>>>  never = maxBound :: Microseconds
>>>
>>>  schedule :: MVar ScheduleInput -> MVar a -> Stack a -> IO ()
>>>  schedule inpVar wnVar stack = schedule_ never stack
>>>  where
>>>    schedule_ :: Microseconds -> Stack -> IO ()
>>>    schedule_ timeout stack = do
>>>        now <- getSystemTime
>>>        let tillTimeout = 0 `max` (timeout - now)
>>>        if tillTimeout == 0 && not (isEmpty stack) then do
>>>            let (val, stack') = pop stack
>>>            putMVar wnVar (PopValue val)
>>>            schedule never stack'
>>>          else do
>>>            inp <- takeMVarWithTimeout (fromIntegral tillTimeout) inpVar
>>>            case inp of
>>>                ModifyStack f -> schedule_ timeout (f stack)
>>>                WaitFor t        -> do
>>>                    now <- getSystemTime
>>>                    schedule (t+now) stack
>>>                Timeout        -> schedule timeout stack
>>>
>>>  readMVarWithTimeout :: Int -> MVar ScheduleInput -> IO ScheduleInput
>>>  readMVar timeoutUS inpVar = do
>>>    tid <- forkIO $ do
>>>        threadDelay timeoutUS
>>>        putMVar inpVar Timeout
>>>    inp <- takeMVar inpVar
>>>    killThread tid
>>>    return inp
>>>
>>>  waitNotify :: MVar ScheduleInput -> MVar Int -> IO ()
>>>  waitNotify schInp wnInp = do
>>>    val <- takeMVar wnInp
>>>    ...notify...
>>>    let t = ....
>>>    putMVar schInp $ WaitFor t  -- block input for the specified period
>>>
>>>  main = do
>>>    schVar <- newEmptyMVar
>>>    wnVar <- newEmptyMVar
>>>    forkIO $ schedule schVar wnVar []
>>>    forkIO $ waitNotify wnVar schVar
>>>    ...
>>>    -- Modify stack according to user input inside your main IO loop
>>>    putMVar schVar $ ModifyStack $ \stack -> ...
>>>
>>>
>>>  I'm sure this is not exactly what you want, but at least it illustrates
>>>  how you can achieve anything you like by using MVars + extra worker
>>>  threads + killing threads (useful for implementing timeouts).
>>>
>>>
>>>  Steve
>>>
>>>  Floptical Logic wrote:
>>>>
>>>>  Hi,
>>>>
>>>>  I am new to concurrency in Haskell and I am having trouble
>>>>  implementing the notion of interrupting a thread.
>>>>
>>>>  In a new thread, call it waitNotify, I am trying to do the following:
>>>>  pop a number from a stack, wait some number of seconds based on the
>>>>  number popped from the stack, perform some notification, and repeat
>>>>  until there are no more numbers in the stack at which point we wait
>>>>  for a new number.
>>>>
>>>>  These numbers will be supplied interactively by the user from main.
>>>>  When the user supplies a new number, I want to interrupt whatever
>>>>  waiting is happening in waitNotify, insert the number in the proper
>>
>>  >> position in the current stack, and resume waitNotify using the updated
>>>>
>>>>  stack.  Note, here "stack" is just a generalization; it will likely
>>>>  just be a list.
>>>>
>>>>  What is the most idiomatic way to capture this sort of behavior in
>>>>  Haskell?  My two challenges are the notion of interrupting a thread,
>>>>  and sharing and updating this stack between threads (main and
>>>>  waitNotify).
>>>>
>>>>  Thank you
>>>>  _______________________________________________
>>>>  Beginners mailing list
>>>>  [email protected]
>>>>  http://www.haskell.org/mailman/listinfo/beginners
>>>>
>>>  _______________________________________________
>>>  Beginners mailing list
>>>  [email protected]
>>>  http://www.haskell.org/mailman/listinfo/beginners
>>>
>>
>> Thanks Stephen.  That worked and things are starting to make more
>> sense.  The crux of it all was the readMVarWithTimeout function which
>> does exactly what I want.
>>
>> Now I want to extend this a bit further to use StateT.  I've modified
>> the schedule function quite a bit, and now it has type schedule ::
>> StateT MyState IO.  I keep the MVar actVar in MyState as well the list
>> (stack) of wait times.  However, the type of forkIO is forkIO :: IO ()
>> -> IO ThreadId.  How do I fork a new thread for schedule even though
>> it is wrapped in the State monad?
>>
>> Thanks again.
>
> You'll want something like this:
>
> myFork :: StateT MyState IO () -> MyState -> StateT MyState IO ThreadId
> myFork action initialState = liftIO (forkIO (evalStateT action
> initialState))
>
> Dean
>

That's not quite what I'm looking for.  I don't want to create a new
thread in which to run the monad but rather to be able to create
threads from inside the monad (as a result of running the monad).


------------------------------

Message: 6
Date: Thu, 31 Dec 2009 12:26:28 +0100
From: Chadda? Fouch? <[email protected]>
Subject: Re: [Haskell-beginners] Interrupting a thread
To: Floptical Logic <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

On Thu, Dec 31, 2009 at 9:21 AM, Floptical Logic
<[email protected]> wrote:
>> You'll want something like this:
>>
>> myFork :: StateT MyState IO () -> MyState -> StateT MyState IO ThreadId
>> myFork action initialState = liftIO (forkIO (evalStateT action
>> initialState))
>
> That's not quite what I'm looking for.  I don't want to create a new
> thread in which to run the monad but rather to be able to create
> threads from inside the monad (as a result of running the monad).

And that's what this code does. Do you want it to automatically use
the state of the monad ?

> myFork :: StateT MyState IO () -> MyState -> StateT MyState IO ThreadId
> myFork action = liftIO . forkIO . evalStateT action =<< get

keep in mind that nothing the thread will do will affect the state of
the main thread.

-- 
Jedaï


------------------------------

Message: 7
Date: Thu, 31 Dec 2009 12:53:05 +0100
From: legajid <[email protected]>
Subject: [Haskell-beginners] Data.Map, types and debug
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Hi, 
studying IO with files, i got this tutorial program.
By the way, i discover the Data.Map module.
Several questions then come to my mind :
q1: why, in mapM_, make (sort (keys grades)) ? keys is already sorted, isn't it?
q2: why, in mapM_, have grades twice (in draw then keys).
        I wonder if writing only draw grades, one could then extract the s and 
g parts in the draw function (via keys and elems).
        From this, i have problems with the type of grades; which is it? The 
insert function, using insertWith should give 
        Map k a, but foldr seems to change this (couldn't match expected type 
[Map k a] against inferred type Map [String] a1
        on the mapM_ line .
q3: To solve the types problem, I tried to debug : i can get the types for s, 
marks and avg but for g, it says not in scope.
    How can i get this information ?
q4: I also tried to type the parameter in draw (draw (x::Map k a) = ...) but i 
got an error :
        Illegal signature in pattern
        use -XScopedTypeVariables to permit it
        Since this parameter is visibly not set by default in ghci, is it a 
good idea to set it ?

Thanks and happy new year.
Didier


    import Data.Char 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char>
    import Data.Maybe 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe>
    import Data.List
    import Data.Map hiding (map 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map>)
    import Text.Printf

    main = do
        src <- readFile 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:readFile>
 "grades"
        let pairs   = map 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map> 
(split.words 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:words>) 
(lines 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:lines> 
src)
        let grades  = foldr 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:foldr> 
insert empty pairs
        mapM_ 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:mapM_> 
(draw grades) (sort (keys grades))
      where
        insert (s, g) = insertWith (++ 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:.>) s [g]
        split [name,mark] = (name, read 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:read> 
mark)
 
    draw g s = printf "%s\t%s\tAverage: %f\n" s (show 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show> 
marks) avg
      where
        marks = findWithDefault (error 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error> 
"No such student") s g
        avg   = sum 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum> 
marks / fromIntegral 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fromIntegral>
 (length 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:length> 
marks) :: Double 
<http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Double>




------------------------------

_______________________________________________
Beginners mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/beginners


End of Beginners Digest, Vol 18, Issue 31
*****************************************

Reply via email to