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. Re: adding state handing to existing code (Stephen Tetley)
2. getChar and keyboard reading (Matthias G?demann)
3. Re: getChar and keyboard reading (Magnus Therning)
4. Re: getChar and keyboard reading (Daniel Fischer)
5. Re: adding state handing to existing code
(Stephen Blackheath [to Haskell-Beginners])
6. Re: getChar and keyboard reading (Matthias G?demann)
7. Re: if statements (Christian Maeder)
8. Re: adding state handing to existing code (Scott Thoman)
----------------------------------------------------------------------
Message: 1
Date: Sun, 24 Jan 2010 10:02:10 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] adding state handing to existing code
Cc: [email protected]
Message-ID:
<[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
Hello Scott
Here's the "simplest solution" I can come up with.
It uses literate Haskell (code lines begin with >) - rather than
normal Haskell. It means I can check the code as I write it rather
than post rubbish. Copy pate it into a file with .lhs as the extension
or remove the > and first space.
> {-# LANGUAGE FlexibleContexts #-}
> module UseState where
> import Control.Monad.State
> import Text.Printf
> process :: Integer -> Integer -> StateT Integer IO Integer
> process x y = do
> s <- get
> put $ s + 1
> return $ 2 * x * y
> doit :: StateT Integer IO ()
> doit = do
> ans <- process 42 43
> liftIO $ printf "f x y = %d\n" ans
> main :: IO ()
> main = do
> runStateT doit 0
> putStrLn "done"
Now I wouldn't argue that this simple solution is particularly simple
- its merit is only that it is the closest I could get to your
original.
Because 'process' is now a monadic function 'doit' has to change - it
can't apply printf "..." to process 42 43 anymore, instead it has to
bind the result of process 42 43 to the temporary variable 'ans' and
use that (there are ways to avoid using temporary bindings but for the
moment they would make things more complicated).
Also 'printf' is in the IO monad - and whereas 'process' is "in" the
state monad. To use one monad within another, you need one monad to be
the base monad and one monad to be a transformer. Here IO is the base
monad and State is the transformer (IO is
special it can only be a base monad and never a transformer). Because
the State monad is now a transformer I had to use the StateT
transformer version rather than the regular State version - that's why
I used the exaggerated quotes for '"in" the state monad' above. To use
'printf' you have to lift it from the base monad so it can be used
within the transformer monad - hence the prefix of 'liftIO' to the
call to 'printf'.
As the code now uses the transformer version of the state monad, this
mandates a change to 'process' as well as its type needs to be
compatible with the transformer+base monad rather than the previous
State monad.
All in all there are quite a lot of changes to do something that
superficially at least should seem simple to do. If there's an ah-ha
moment its probably more anticipating want effects (state, error
handling, logging - writer monad, reader monad for a read-only
'environment' - e.g. configuration data, ...) you want the monad to
have. Taking pure code to monadic code is a burden, but adding another
effect to monadic code is much less so (though again IO is a bit of a
problem as it can only be a base monad and operations from IO must
always be lifted with 'liftIO' other monads use plain 'lift').
Some things you can do to minimise later changes are define an alias
for your monad, e.g:
> type PMonad ans = StateT Integer IO ans
> processP :: Integer -> Integer -> PMonad Integer
> processP x y = do
> s <- get
> put $ s + 1
> return $ 2 * x * y
> doitP :: PMonad ()
> doitP = do
> ans <- processP 42 43
> liftIO $ printf "f x y = %d\n" ans
> main_alt :: IO ()
> main_alt = do
> runStateT doitP 0
> putStrLn "done"
A better idiom - more flexible, but more abstract - is rather than
have your monadic operations depend on a concrete monad, is to make
them depend on a monad transformers signature (for instance the state
transformer has the corresponding type class MonadState for its
signature):
> processAbstract :: MonadState Integer m => Integer -> Integer -> m Integer
> processAbstract x y = do
> s <- get
> put $ s + 1
> return $ 2 * x * y
Best wishes
Stephen
------------------------------
Message: 2
Date: Sun, 24 Jan 2010 21:49:59 +0100
From: Matthias G?demann <[email protected]>
Subject: [Haskell-beginners] getChar and keyboard reading
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii
Hi,
I wrote a program which should read the number of key presses in a
given time. It forks a thread which calls getChar and increases a MVar
each time getChar suceeds. After a delay (here 2s) the MVar is read,
its value is printed and the program exits.
import Control.Concurrent
increaseEveryPush mVCount = do
_ <- getChar
inh <- takeMVar mVCount
putMVar mVCount (inh + 1)
increaseEveryPush mVCount
main = do
x <- newMVar 0
forkIO (increaseEveryPush x)
threadDelay 2000000
inh <- takeMVar x
putStr $ "\n" ++ (show inh) ++ " times button pushed\n"
But this does not work, as getChar does not succeed if there is no EOF
given (^D). It normally just exits with 0 as value in the MVar. Is
there a way toread the keyboard without having to terminate with EOF?
regards,
Matthias
------------------------------
Message: 3
Date: Sun, 24 Jan 2010 21:00:49 +0000
From: Magnus Therning <[email protected]>
Subject: Re: [Haskell-beginners] getChar and keyboard reading
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="utf-8"
On 24/01/10 20:49, Matthias Güdemann wrote:
>
> Hi,
>
> I wrote a program which should read the number of key presses in a
> given time. It forks a thread which calls getChar and increases a MVar
> each time getChar suceeds. After a delay (here 2s) the MVar is read,
> its value is printed and the program exits.
>
>
> import Control.Concurrent
>
> increaseEveryPush mVCount = do
> _ <- getChar
> inh <- takeMVar mVCount
> putMVar mVCount (inh + 1)
> increaseEveryPush mVCount
>
> main = do
> x <- newMVar 0
> forkIO (increaseEveryPush x)
> threadDelay 2000000
> inh <- takeMVar x
> putStr $ "\n" ++ (show inh) ++ " times button pushed\n"
>
>
> But this does not work, as getChar does not succeed if there is no EOF
> given (^D). It normally just exits with 0 as value in the MVar. Is
> there a way toread the keyboard without having to terminate with EOF?
In the past I've done this sort of thing by turning of buffering on stdin:
hSetBuffering stdin NoBuffering
/M
--
Magnus Therning (OpenPGP: 0xAB4DFBA4)
magnusï¼ therningï¼org Jabber: magnusï¼ therningï¼org
http://therning.org/magnus identi.ca|twitter: magthe
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: OpenPGP digital signature
Url :
http://www.haskell.org/pipermail/beginners/attachments/20100124/2ea9b110/signature-0001.bin
------------------------------
Message: 4
Date: Sun, 24 Jan 2010 22:06:19 +0100
From: Daniel Fischer <[email protected]>
Subject: Re: [Haskell-beginners] getChar and keyboard reading
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"
Am Sonntag 24 Januar 2010 21:49:59 schrieb Matthias Güdemann:
> Hi,
>
> I wrote a program which should read the number of key presses in a
> given time. It forks a thread which calls getChar and increases a MVar
> each time getChar suceeds. After a delay (here 2s) the MVar is read,
> its value is printed and the program exits.
>
>
> import Control.Concurrent
>
> increaseEveryPush mVCount = do
> _ <- getChar
> inh <- takeMVar mVCount
> putMVar mVCount (inh + 1)
> increaseEveryPush mVCount
>
> main = do
> x <- newMVar 0
> forkIO (increaseEveryPush x)
> threadDelay 2000000
> inh <- takeMVar x
> putStr $ "\n" ++ (show inh) ++ " times button pushed\n"
>
>
> But this does not work, as getChar does not succeed if there is no EOF
> given (^D).
No, a newline would suffice. But you could set the buffering of stdin to
NoBuffering.
main = do
hSetBuffering stdin NoBuffering
x <- newMVar 0
forkIO (increaseEveryPush x)
threadDelay 2000000
inh <- takeMVar x
putStr $ "\n" ++ (show inh) ++ " times button pushed\n"
$ ./keyPress
uzfgoigzoruizhuiorhguioegu
26 times button pushed
It probably won't work on Windows, though.
> It normally just exits with 0 as value in the MVar. Is
> there a way toread the keyboard without having to terminate with EOF?
>
> regards,
> Matthias
------------------------------
Message: 5
Date: Mon, 25 Jan 2010 10:11:48 +1300
From: "Stephen Blackheath [to Haskell-Beginners]"
<[email protected]>
Subject: Re: [Haskell-beginners] adding state handing to existing code
To: Scott Thoman <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8
Scott,
Here's the most straightforward way to do it:
--
process :: Integer -> Integer -> StateT Int IO Integer
process x y = do
s <- get
put $ s + 1
return $ 2 * x * y
doit :: StateT Int IO ()
doit = do
p <- process 42 43
liftIO $ printf "f x y = %d\n" p
main :: IO ()
main = do
n <- execStateT doit 0
putStrLn $ "done "++show n++" times"
--
One thing you'll note is that the type of 'doit' has changed. There's
no way to pass state "through" a function without it being reflected in
the type, and in many ways, that's the point of Haskell - to make
potentially dangerous things explicit. An alternative is to use an
IORef, but that makes your code completely imperative style, which is
not very Haskellish.
One thing you'll notice is that process is now in IO, which is not
desirable, since it's pure. On occasions I've written this helper function:
-- | Adapt a StateT to a pure state monad.
purely :: Monad m => State s a -> StateT s m a
purely code = do
s <- get
let (ret, s') = runState code s
put s'
return ret
With this you could re-write it as...
--
process :: Integer -> Integer -> State Int Integer
process x y = do
s <- get
put $ s + 1
return $ 2 * x * y
doit :: StateT Int IO ()
doit = do
p <- purely $ process 42 43
liftIO $ printf "f x y = %d\n" p
--
Monad transformer stacks aren't perfect, but they're good if used
appropriately. If you use them a lot, then it can lead to a necessity
to unstack and re-stack them like I did here. I think monads work best
if you initially think of your code in plain Haskell terms, and
introduce them later as a convenience.
As I'm sure you know, the "Haskell way" is to make code as pure as
possible, using IO types only where necessary.
Steve
Scott Thoman wrote:
> Since I'm very new to Haskell I have what is probably a simple
> question yet I'm having trouble finding a clear example of how it
> works. The basic question is: how do I pass state through existing
> code without the intermediate code knowing about it. If I have, for
> example, several layers of function calls and the innermost function
> needs to access some state that is only "seeded" by the outermost
> function, how do I do that without the functions in between knowing
> about the additional state being threaded through them?
>
> I have a simple example (that may *not* be good idiomatic Haskell):
>
> --
> process :: Integer -> Integer -> Integer
> process x y =
> 2 * x * y
>
> doit :: IO ()
> doit = do
> printf "f x y = %d\n" $ process 42 43
>
> main :: IO ()
> main = do
> doit
> putStrLn "done"
> --
>
> (I'm not totally sure about the type of "doit" but the code compiles
> and runs as expected)
>
> What I want to do is add some state handing to "process" to have it,
> say, count the number of times it's been called (putting
> threading/thread-local concerns aside for the moment). I'm trying to
> understand how to add state to "process" along the lines of:
>
> --
> process :: Integer -> Integer -> State Integer Integer
> process x y = do
> s <- get
> put $ s + 1
> return $ 2 * x * y
> --
>
> but I want to only seed the state from "main" without "doit" having to
> change -- I can call "process" from "doit" like "(execState (process
> 42 43) 0)" but I want the initial state to be determined at the top
> level, from main.
>
> I have a feeling there's some kind of "ah ha" moment that I'm just not
> seeing yet. Any help or pointers to where I can look for myself would
> be greatly appreciated.
>
> Thanks in advance,
>
> -thor
> _______________________________________________
> Beginners mailing list
> [email protected]
> http://www.haskell.org/mailman/listinfo/beginners
>
------------------------------
Message: 6
Date: Sun, 24 Jan 2010 22:40:32 +0100
From: Matthias G?demann <[email protected]>
Subject: Re: [Haskell-beginners] getChar and keyboard reading
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=us-ascii
> In the past I've done this sort of thing by turning of buffering on stdin:
>
> hSetBuffering stdin NoBuffering
thanks, works well that way
> It probably won't work on Windows, though.
ok, no Problem atm
regards
Matthias
------------------------------
Message: 7
Date: Mon, 25 Jan 2010 12:54:03 +0100
From: Christian Maeder <[email protected]>
Subject: [Haskell-beginners] Re: if statements
To: John Moore <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
John Moore schrieb:
>
> data Expression = Val Integer
> | Add Expression Expression
> | Subtract Expression Expression
> | Multiply Expression Expression
> | Divide Expression Expression
> deriving Show
After you've copied your code (several times) for the four cases
Add, Subtract, Multiply, and Divide, you may want to consider:
data Expression = Val Integer
| OpExpr Op Expression Expression
data Op = Add | Subtract | Multiply | Divide
op2op :: Op -> Integer -> Integer -> Integer
op2op op = case op of
Add -> (+)
Subtract -> (-)
Multiply -> (*)
Divide -> div
(or: type Op = Integer -> Integer -> Integer)
Cheers Christian
------------------------------
Message: 8
Date: Mon, 25 Jan 2010 12:58:32 -0500
From: Scott Thoman <[email protected]>
Subject: Re: [Haskell-beginners] adding state handing to existing code
To: "Stephen Blackheath [to Haskell-Beginners]"
<[email protected]>,
[email protected]
Cc: [email protected]
Message-ID:
<[email protected]>
Content-Type: text/plain; charset=UTF-8
Thank you guys very much for the quick responses. This is very useful
info and I've definitely got more reading and learning to do - in
particular, the whole lifting/transforming/stacking monads area. Part
of this exercise of learning Haskell is learning how to do things with
a pure functional approach and so I'm thinking about things that might
happen while building and maintaining software. In this scenario I
was imagining that the "doit" function was something over which I
might not have control. I like the idea that you can't just jam state
into the code without the type system, and everyone involved, knowing
about it. So my question is now evolving into looking at it the other
way around - from the designer of "doit".
If I were designing something, for a very simple example, like the map
function but maybe over some custom sequence-like thing, how could I
make it so that the user-supplied function could be monadic/stateful
or not? Is there a way to make the map function flexible enough so
that the author of the function argument could make it stateful or
pure without any control over the definition of map itself?
That question doesn't really need an answer that just my reasoning at
this point - one of those "what if I had written software with Haskell
and a high priority requirement came along, how would I handle it"
kind of questions. It's an interesting exercise to think about
applying a purely functional approach to something might happen in day
to day development.
-stt
On Sun, Jan 24, 2010 at 4:11 PM, Stephen Blackheath [to
Haskell-Beginners] <[email protected]>
wrote:
> Scott,
>
> Here's the most straightforward way to do it:
>
> --
> process :: Â Integer -> Integer -> StateT Int IO Integer
> process x y = do
> Â Â s <- get
> Â Â put $ s + 1
> Â Â return $ 2 * x * y
>
> doit :: StateT Int IO ()
> doit = do
> Â Â p <- process 42 43
> Â Â liftIO $ printf "f x y = %d\n" p
>
> main :: IO ()
> main = do
> Â Â n <- execStateT doit 0
> Â Â putStrLn $ "done "++show n++" times"
> --
>
> One thing you'll note is that the type of 'doit' has changed. Â There's
> no way to pass state "through" a function without it being reflected in
> the type, and in many ways, that's the point of Haskell - to make
> potentially dangerous things explicit. Â An alternative is to use an
> IORef, but that makes your code completely imperative style, which is
> not very Haskellish.
>
> One thing you'll notice is that process is now in IO, which is not
> desirable, since it's pure. Â On occasions I've written this helper function:
>
> -- | Adapt a StateT to a pure state monad.
> purely :: Monad m => State s a -> StateT s m a
> purely code = do
> Â Â s <- get
> Â Â let (ret, s') = runState code s
> Â Â put s'
> Â Â return ret
>
> With this you could re-write it as...
>
> --
> process :: Â Integer -> Integer -> State Int Integer
> process x y = do
> Â Â s <- get
> Â Â put $ s + 1
> Â Â return $ 2 * x * y
>
> doit :: StateT Int IO ()
> doit = do
> Â Â p <- purely $ process 42 43
> Â Â liftIO $ printf "f x y = %d\n" p
> --
>
> Monad transformer stacks aren't perfect, but they're good if used
> appropriately. Â If you use them a lot, then it can lead to a necessity
> to unstack and re-stack them like I did here. Â I think monads work best
> if you initially think of your code in plain Haskell terms, and
> introduce them later as a convenience.
>
> As I'm sure you know, the "Haskell way" is to make code as pure as
> possible, using IO types only where necessary.
>
>
> Steve
>
> Scott Thoman wrote:
>> Since I'm very new to Haskell I have what is probably a simple
>> question yet I'm having trouble finding a clear example of how it
>> works. Â The basic question is: how do I pass state through existing
>> code without the intermediate code knowing about it. Â If I have, for
>> example, several layers of function calls and the innermost function
>> needs to access some state that is only "seeded" by the outermost
>> function, how do I do that without the functions in between knowing
>> about the additional state being threaded through them?
>>
>> I have a simple example (that may *not* be good idiomatic Haskell):
>>
>> --
>> process :: Â Integer -> Integer -> Integer
>> process x y =
>> Â Â 2 * x * y
>>
>> doit :: IO ()
>> doit = do
>> Â Â printf "f x y = %d\n" $ process 42 43
>>
>> main :: IO ()
>> main = do
>> Â Â doit
>> Â Â putStrLn "done"
>> --
>>
>> (I'm not totally sure about the type of "doit" but the code compiles
>> and runs as expected)
>>
>> What I want to do is add some state handing to "process" to have it,
>> say, count the number of times it's been called (putting
>> threading/thread-local concerns aside for the moment). Â I'm trying to
>> understand how to add state to "process" along the lines of:
>>
>> --
>> process :: Â Integer -> Integer -> State Integer Integer
>> process x y = do
>> Â Â s <- get
>> Â Â put $ s + 1
>> Â Â return $ 2 * x * y
>> --
>>
>> but I want to only seed the state from "main" without "doit" having to
>> change -- I can call "process" from "doit" like "(execState (process
>> 42 43) 0)" but I want the initial state to be determined at the top
>> level, from main.
>>
>> I have a feeling there's some kind of "ah ha" moment that I'm just not
>> seeing yet. Â Any help or pointers to where I can look for myself would
>> be greatly appreciated.
>>
>> Thanks in advance,
>>
>> -thor
>> _______________________________________________
>> 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 19, Issue 24
*****************************************