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.  Enumerated types (legajid)
   2. Re:  Re: Re: Design Question: fmap with two lists (Brent Yorgey)
   3. Re:  Enumerated types (Patrick LeBoutillier)
   4. Re:  Enumerated types (Brent Yorgey)
   5.  Re: Interrupting a thread (Maciej Piechotka)
   6. Re:  Enumerated types (legajid)
   7.  parser for expressions (John Moore)
   8. Re:  parser for expressions (Stephen Tetley)
   9. Re:  Interrupting a thread
      (Stephen Blackheath [to Haskell-Beginners])


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

Message: 1
Date: Sun, 27 Dec 2009 14:42:48 +0100
From: legajid <[email protected]>
Subject: [Haskell-beginners] Enumerated types
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Hello,

I have some trouble evaluating Enum class.
Following is my source:

data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire 
deriving (Enum, Show)

auths=[Buzzati .. Verne] ++ enumFrom Ray
pref=take 3 auths
-- 1 disp_pref=mapM_ (putStrLn) pref

auth1 = Buzzati
auth2 = succ auth1       -- Werber
auth3 = pred Asimov      -- Ray
num_auth4=fromEnum Verne -- 2
-- 2 toEnum

main= display Buzzati
display x = do
        putStrLn (show x)
        display (succ x)
-- 3 end of enum

1. could'nt match expected type [Char] against inferred type Authors
I would like to display each data constructor name on one line , giving :
Buzzati
Werber
Verne
How can i translate data from one type to another (Authors to [Char])?

2. Like fromEnum gives data constructor index, is it possible with 
toEnum (or other way) to get the nth constructor of the given type ?
eg : 2 applied to Authors (not in scope ?) would give Verne

3. tried to take  'succ' of last tag  in  enumeration
How to detect the end of an enumeration ? Can i get the maxbound index ?

Thanks,
Didier.





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

Message: 2
Date: Sun, 27 Dec 2009 09:07:35 -0500
From: Brent Yorgey <[email protected]>
Subject: Re: [Haskell-beginners] Re: Re: Design Question: fmap with
        two lists
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii

On Sat, Dec 26, 2009 at 06:12:00PM +0100, Maciej Piechotka wrote:
> On Fri, 2009-12-25 at 21:10 -0500, Brent Yorgey wrote:
> > There is such a class in the category-extras package, although it is
> > so general that it is probably not worth the effort of trying to
> > understand it unless you really need the extra abstraction.
> > 
> > -Brent
> 
> For the record - what is the name of it? I tried to search through
> category-extras twice.

Control.Functor.Bifunctor.  It took me a while to find it, too (I've
had to re-find it several times); I didn't actually say where to find
it in my first email because I knew it would take me a long time.
Unfortunately, coherent organization is not among category-extras'
strengths. ;-)

-Brent


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

Message: 3
Date: Sun, 27 Dec 2009 09:10:21 -0500
From: Patrick LeBoutillier <[email protected]>
Subject: Re: [Haskell-beginners] Enumerated types
To: legajid <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Hi,

On Sun, Dec 27, 2009 at 8:42 AM, legajid <[email protected]> wrote:
> Hello,
>
> I have some trouble evaluating Enum class.
> Following is my source:
>
> data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving
> (Enum, Show)
>
> auths=[Buzzati .. Verne] ++ enumFrom Ray
> pref=take 3 auths
> -- 1 disp_pref=mapM_ (putStrLn) pref

putStrLn wants a String as argument, here you are passing an Authors. Try this:

disp_pref=mapM_ (putStrLn . show) pref

>
> auth1 = Buzzati
> auth2 = succ auth1       -- Werber
> auth3 = pred Asimov      -- Ray
> num_auth4=fromEnum Verne -- 2
> -- 2 toEnum

You can use toEnum to get the nth constructor. For example:

nthAuthor :: Int -> Authors
nthAuthor i = toEnum i

>
> main= display Buzzati
> display x = do
>       putStrLn (show x)
>       display (succ x)
> -- 3 end of enum

To use maxBound you need to make your type an instance of Bounded. You
will also need to make it an instance of Eq in order to compare it.

main= display Buzzati
display x = do
      putStrLn (show x)
      if x == maxBound
        then return ()
        else display (succ x)


Patrick

>
> 1. could'nt match expected type [Char] against inferred type Authors
> I would like to display each data constructor name on one line , giving :
> Buzzati
> Werber
> Verne
> How can i translate data from one type to another (Authors to [Char])?
>
> 2. Like fromEnum gives data constructor index, is it possible with toEnum
> (or other way) to get the nth constructor of the given type ?
> eg : 2 applied to Authors (not in scope ?) would give Verne
>
> 3. tried to take  'succ' of last tag  in  enumeration
> How to detect the end of an enumeration ? Can i get the maxbound index ?
>
> Thanks,
> Didier.
>
>
>
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>



-- 
=====================
Patrick LeBoutillier
Rosemère, Québec, Canada


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

Message: 4
Date: Sun, 27 Dec 2009 09:14:45 -0500
From: Brent Yorgey <[email protected]>
Subject: Re: [Haskell-beginners] Enumerated types
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii

On Sun, Dec 27, 2009 at 02:42:48PM +0100, legajid wrote:
> Hello,
>
> I have some trouble evaluating Enum class.
> Following is my source:
>
> data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving 
> (Enum, Show)
>
> auths=[Buzzati .. Verne] ++ enumFrom Ray
> pref=take 3 auths
> -- 1 disp_pref=mapM_ (putStrLn) pref

This is a type error since putStrLn expects a String and pref is a
list of Authors.  But the 'deriving Show' means that you can use the
'show' function to convert:

  disp_pref = mapM_ (putStrLn . show) pref

In fact, since  print = putStrLn . show, you can just say

  disp_pref = mapM_ print pref

> 2. Like fromEnum gives data constructor index, is it possible with toEnum 
> (or other way) to get the nth constructor of the given type ?
> eg : 2 applied to Authors (not in scope ?) would give Verne

Yes, with toEnum.  Just use e.g. 'toEnum 2'.  How does it know that
you want an Author and not some other Enum type?  Why, through the
magic of type inference!  As long as you use 'toEnum 2' in a context
where an Author value is expected it will evaluate to Verne.

> 3. tried to take  'succ' of last tag  in  enumeration
> How to detect the end of an enumeration ? Can i get the maxbound index ?

Yes, if you add 'Bounded' to the list of derived classes, then
'maxBound' gives you the last one.

-Brent


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

Message: 5
Date: Sun, 27 Dec 2009 17:35:20 +0100
From: Maciej Piechotka <[email protected]>
Subject: [Haskell-beginners] Re: Interrupting a thread
To: [email protected]
Message-ID: <1261931720.5658.7.ca...@picard>
Content-Type: text/plain; charset="UTF-8"

On Sat, 2009-12-26 at 23:11 -0600, 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

1. Hmm. IMHO - maybe you should look on CHP. As far as I remeber
writing/reading to channel there is blocking.

2. You mean stack (FILO) or queue (FIFO)?

3. Why don't just read lazily from input? 

Regards




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

Message: 6
Date: Sun, 27 Dec 2009 18:17:34 +0100
From: legajid <[email protected]>
Subject: Re: [Haskell-beginners] Enumerated types
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Thanks.

for 1, i tried mapM ( putStrLn) (show pref) but show  gives only one 
line with all values, instead of n lines with 1 value. I now understand 
that show must be in the function that is mapped.
for 2, ok
for 3, ok with new classes in deriving. I thought that i would have to 
write new instances of Bounded or Eq, but now i think it's unuseful 
since standard functions exist in these classes.


Patrick LeBoutillier a écrit :
> Hi,
>
> On Sun, Dec 27, 2009 at 8:42 AM, legajid <[email protected]> wrote:
>   
>> Hello,
>>
>> I have some trouble evaluating Enum class.
>> Following is my source:
>>
>> data Authors= Buzzati | Werber | Verne | Ray | Asimov | Voltaire deriving
>> (Enum, Show)
>>
>> auths=[Buzzati .. Verne] ++ enumFrom Ray
>> pref=take 3 auths
>> -- 1 disp_pref=mapM_ (putStrLn) pref
>>     
>
> putStrLn wants a String as argument, here you are passing an Authors. Try 
> this:
>
> disp_pref=mapM_ (putStrLn . show) pref
>
>   
>> auth1 = Buzzati
>> auth2 = succ auth1       -- Werber
>> auth3 = pred Asimov      -- Ray
>> num_auth4=fromEnum Verne -- 2
>> -- 2 toEnum
>>     
>
> You can use toEnum to get the nth constructor. For example:
>
> nthAuthor :: Int -> Authors
> nthAuthor i = toEnum i
>
>   
>> main= display Buzzati
>> display x = do
>>       putStrLn (show x)
>>       display (succ x)
>> -- 3 end of enum
>>     
>
> To use maxBound you need to make your type an instance of Bounded. You
> will also need to make it an instance of Eq in order to compare it.
>
> main= display Buzzati
> display x = do
>       putStrLn (show x)
>       if x == maxBound
>         then return ()
>         else display (succ x)
>
>
> Patrick
>
>   
>> 1. could'nt match expected type [Char] against inferred type Authors
>> I would like to display each data constructor name on one line , giving :
>> Buzzati
>> Werber
>> Verne
>> How can i translate data from one type to another (Authors to [Char])?
>>
>> 2. Like fromEnum gives data constructor index, is it possible with toEnum
>> (or other way) to get the nth constructor of the given type ?
>> eg : 2 applied to Authors (not in scope ?) would give Verne
>>
>> 3. tried to take  'succ' of last tag  in  enumeration
>> How to detect the end of an enumeration ? Can i get the maxbound index ?
>>
>> Thanks,
>> Didier.
>>
>>
>>
>> _______________________________________________
>> Beginners mailing list
>> [email protected]
>> http://www.haskell.org/mailman/listinfo/beginners
>>
>>     
>
>
>
>   


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

Message: 7
Date: Sun, 27 Dec 2009 18:10:54 +0000
From: John Moore <[email protected]>
Subject: [Haskell-beginners] parser for expressions
To: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"

Hi,
    What I'm trying to do is create a parser so as when I enter say 1+1 it
will return Add(Val 1)(Val 1). A couple of questions do I have to state
three basic parser. As in item, fail, synbol and then combine them with
below. And by the way the one below seems to be all wrong.



parse  :: String -> expr
parse expr = [(expr,string)]
expr :: Parser value
expr =  do t <- term
  do char '+'
  e <- expr
    return Add (Val t)(Val e)
 +++ return t

(+++) :: Parser a -> Parser a -> Parser a
t +++ w  inp  = case t inp of
     []  ->  w inp
     [(v,out)] -> [(v,out)]


This is what I mean by item fail and symbol

type Parser s a = [s] -> [(a,[s])]
item [] = []
item (c:cs) = [(c,cs)]
pFail :: Parser s a
pFail = \cs -> []
pSymbol :: Eq s => s -> Parser s s
pSymbol a (b:bs) |a == b = [(b,bs)]
  |otherwise = []

I know this is a bit of a mess, but could someone explain where I should
start and if I should use any of the code above. Also to point out I want to
write the complete parser without using prelude and other built in functions
as I will be changing as I go.

John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
http://www.haskell.org/pipermail/beginners/attachments/20091227/66c806cd/attachment-0001.html

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

Message: 8
Date: Sun, 27 Dec 2009 19:11:24 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] parser for expressions
To: John Moore <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

Hi John

Are you working from the "Monadic Parser Combinators" paper by Graham
Hutton and Erik Meijer?


That was written for Gofer a predecessor to Haskell which is similar
Haskell but has some slight differences - particularly in Haskell you
would really want to make the Parser a newtype then use can make a
Monad instance.

Here are some of the bits from that paper with the newtype for Parser
- unfortunately it adds some clutter. I think there should be a full
version converted to Haskell if you do a web search. You will
certainly need the sat and char parsers from the paper - I can post
them later if you can't find them through a web search:


newtype Parser s a = Parser { getParser :: [s] -> [(a,[s])] }

result :: a -> Parser s a
result v = Parser $ \inp -> [(v,inp)]


bind :: Parser s a -> (a -> Parser s b) -> Parser s b
p `bind` f = Parser $ \inp ->
  concat [ (getParser . f) v inp' | (v,inp') <- (getParser p) inp]


instance Monad (Parser s) where
  return a = result a
  mf >>= k  = mf `bind` k


pFail :: Parser s a
pFail = Parser $ \cs -> []


pSymbol :: Eq s => s -> Parser s s
pSymbol a = Parser $ \inp -> case inp of
                               (b:bs) | a == b -> [(b,bs)]
                               _               -> []





(+++) :: Parser s a -> Parser s a -> Parser s a
t +++ w  = Parser $ \inp -> case (getParser t) inp of
     []  -> (getParser w) inp
     [(v,out)] -> [(v,out)]


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

Message: 9
Date: Mon, 28 Dec 2009 08:47:56 +1300
From: "Stephen Blackheath [to Haskell-Beginners]"
        <[email protected]>
Subject: Re: [Haskell-beginners] Interrupting a thread
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8

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


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

Reply via email to