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. Re:  Critique my program (Roel van Dijk)
   3. Re:  adding state handing to existing code
      (Stephen Blackheath [to Haskell-Beginners])
   4. Re:  adding state handing to existing code (Scott Thoman)
   5.  possible incorrect indentation (John Moore)


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

Message: 1
Date: Mon, 25 Jan 2010 19:34:33 +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

2010/1/25 Scott Thoman <[email protected]>:
> 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?

Hi Scott

[Not quite answering your question directly, but...]

There are monadic versions of the usual 'functionals' map fold - mapM,
foldM. etc

If you don't need to consider other monadic effects (eg. exceptions)
and only need state, some of the common higher order functions are
'stateful'. 'unfoldr' is the most obvious one. 'unfoldr' passes a
state though each recursive step. At each step the 'user function'
looks at the state and decides whether to produce both a new value and
a new state or terminate the computation.

foldr, and foldl too can be seen as stateful. One way to think about
folds (on lists) is that they reduce the list to a summary value, the
summary value is effectively state. If you want to have 'user state'
and still produce a summary value you can pass a pair to the fold
partitioning the user state and summary value.

mapAccumL and mapAccumR from Data.List are variations on this theme -
they combine fold and map, passing an accumulating parameter (a.k.a.
the user state) through the list traversal returning both the new list
and the state.

The unfold version of mapAccumL unfortunately isn't in the standard
library, it lets you traverse the list statefully but has the
additional very useful property that you can escape the traversal
before the end of the list. Here's the definition I use:

-- | @unfoldMap@ is the unfold analogue of accumMapL.
-- We can signal exhaustion early by the Maybe type.
unfoldMap  :: (a -> st -> Maybe (b,st)) -> st -> [a] -> ([b],st)
unfoldMap _ s0 []     = ([],s0)
unfoldMap f s0 (x:xs) = case (f x s0) of
    Nothing       -> ([],s0)
    Just (a,st)   -> (a:as,b) where (as,b) = unfoldMap f st xs

Best wishes

Stephen


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

Message: 2
Date: Mon, 25 Jan 2010 22:13:43 +0100
From: Roel van Dijk <[email protected]>
Subject: Re: [Haskell-beginners] Critique my program
To: David Frey <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1

I realize this is 2 weeks old but I have a few small comments.

> getShipsFromFile :: String -> IO ([ShipPlacement])

The parenthesis around [ShipPlacement] are superfluous.

>hitShip :: [ShipPlacement] -> BoardLocation -> Maybe ShipClass
>hitShip ships loc = case (find (isLocationInShip loc) ships) of
>    Just (ShipPlacement cls _ _) -> Just cls
>    Nothing                      -> Nothing

Also unnecessary parenthesis around the case argument.

And there is a function hidden in your case expression. "find
(isLocationInShip loc) shipsFind" returns a value of type (Maybe
ShipPlacement). Your case converts it to a (Maybe ShipClass). So the
type of the hidden function is (Maybe ShipPlacement -> Maybe
ShipClass). Now look at the type of the fmap function: fmap :: Functor
f => f a -> f b. The last piece of this little puzzle is a function
that converts a ShipPlacement to a ShipClass. Luckily you have already
written it: the field 'placeShip' of the ShipPlacement record.

Maybe has an instance for Functor. This means you can
write the hitShip function like this:

> hitShip :: [ShipPlacement] -> BoardLocation -> Maybe ShipClass
> hitShip ships loc = fmap placeShip $ find (isLocationInShip loc) ships

Next I noticed how your validateShips function checks for erroneous
conditions in a very specific order. First you check for invalid
placements and then for overlapping ships. If the order of these
checks is not important you can write with a bit less plumbing using
the some functions from Data.Maybe:

> validateShips :: [ShipPlacement] -> Maybe GameError
> validateShips ships =
>     listToMaybe $ catMaybes [ validatePlacements ships
>                             , validateOverlap    ships
>                             ]

Hmm, not sure if that is an improvement :-) It would be if there where
more checks.

> isValidPlacement :: ShipPlacement -> Bool
> isValidPlacement (ShipPlacement ship (BoardLocation row col) Vertical) =
>     (col >= 1 && col <= boardWidth) &&
>     (row >= 1 && row <= boardHeight - (shipSize ship - 1))
> isValidPlacement (ShipPlacement ship (BoardLocation col row) Horizontal) =
>     (col >= 1 && col <= boardWidth - (shipSize ship - 1)) &&
>     (row >= 1 && row <= boardHeight)

There is a lot of common code in these 2 equations. This can be made
mode explicit:

> isValidPlacement :: ShipPlacement -> Bool
> isValidPlacement (ShipPlacement ship (BoardLocation row col) o) =
>     case o of
>       Vertical   -> check 0 shipLength
>       Horizontal -> check shipLength 0
>   where
>     check x y = col >= 1 && col <= boardWidth - x &&
>                 row >= 1 && row <= boardHeight - y
>     shipLength = shipSize ship - 1

In general I noticed that you sometimes refer to a value of
ShipPlacement as a 'ship' and sometimes as a 'placement'. I think it
would be a bit easier to read if you are consistent in the naming of
variables.

Overall I would say the quality of the code is not bad at all. It is
easy to follow the flow of the program and the module structure is
sensible.

Regards,
Roel


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

Message: 3
Date: Tue, 26 Jan 2010 10:18:11 +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; format=flowed

Scott,

Generally your code is either written to be monadic or pure, but 
"monadic" can be more or less specific depending on what typeclass is 
used to say it's monadic.  The most general is Monad m =>.

Here's a design where I've encountered this situation, which I think 
might shed some light on the question:  I did a web form editor for 
server-side web applications.  The whole thing was pure, but I realized 
I had a problem:  validators could not access the database.

The thing to do in this situation is to make the type something like:

processForm :: Monad m => Form m -> m Result

where 'Form m' can contain validators with a return type 'm (Either 
String a)' in which validation errors are expressed as, e.g. Left "Value 
must be positive!"

The logic of processForm can be as complex as you like, and written 
completely purely (the generalness of the type Monad m => constrains the 
logic of processForm to be pure), but validators that are passed in as 
arguments can be any monad that the caller wants, e.g. able to access 
the database.  If a particular caller only uses pure validators, 
processForm can be 'run' in the Identity monad.

Using typeclasses, the validators themselves can be expressed with 
capabilities, e.g. validateKeyExists :: ReadableDatabase m => 
...something... -> m (Either String a)

This might mean that it can only read from the database, not write. 
Then the whole thing would only typecheck if processForm was sequenced 
in a monad that gave (at least) read access to the database.


Steve

Scott Thoman wrote:
> 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
>>>
> 


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

Message: 4
Date: Mon, 25 Jan 2010 16:34:28 -0500
From: Scott Thoman <[email protected]>
Subject: Re: [Haskell-beginners] adding state handing to existing code
To: "Stephen Blackheath [to Haskell-Beginners]"
        <[email protected]>
Cc: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset=UTF-8

Now that sounds like what i was imagining too where processForm is
"prepared" to handle the case where the user wants monadic stuff but
can deal with the case where they're pure too - leaving processForm
pure and unchanged.

There sure is a lot to learn with this Haskell stuff.

-stt

On Mon, Jan 25, 2010 at 4:18 PM, Stephen Blackheath [to
Haskell-Beginners] <[email protected]>
wrote:
> Scott,
>
> Generally your code is either written to be monadic or pure, but "monadic"
> can be more or less specific depending on what typeclass is used to say it's
> monadic.  The most general is Monad m =>.
>
> Here's a design where I've encountered this situation, which I think might
> shed some light on the question:  I did a web form editor for server-side
> web applications.  The whole thing was pure, but I realized I had a problem:
>  validators could not access the database.
>
> The thing to do in this situation is to make the type something like:
>
> processForm :: Monad m => Form m -> m Result
>
> where 'Form m' can contain validators with a return type 'm (Either String
> a)' in which validation errors are expressed as, e.g. Left "Value must be
> positive!"
>
> The logic of processForm can be as complex as you like, and written
> completely purely (the generalness of the type Monad m => constrains the
> logic of processForm to be pure), but validators that are passed in as
> arguments can be any monad that the caller wants, e.g. able to access the
> database.  If a particular caller only uses pure validators, processForm can
> be 'run' in the Identity monad.
>
> Using typeclasses, the validators themselves can be expressed with
> capabilities, e.g. validateKeyExists :: ReadableDatabase m =>
> ...something... -> m (Either String a)
>
> This might mean that it can only read from the database, not write. Then the
> whole thing would only typecheck if processForm was sequenced in a monad
> that gave (at least) read access to the database.
>
>
> Steve
>
> Scott Thoman wrote:
>>
>> 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
>>>>
>>
>



-- 
"Very well, then, Mr. Knox, sir.
Let's have a little talk about tweetle beetles...."
- Dr. S.


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

Message: 5
Date: Mon, 25 Jan 2010 22:45:16 +0000
From: John Moore <[email protected]>
Subject: [Haskell-beginners] possible incorrect indentation
To: [email protected]
Message-ID:
        <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"

Hi all,
        Will somebody please explain why this wont run, I sure the code is
right?

data Expression = Val Integer
                | Add Expression Expression
                | Subtract Expression Expression
                | Multiply Expression Expression
                | Divide Expression Expression
         deriving Show
demo1 = (Add(Add(Add(Val 6)(Val 5))(Val 10))(Val 7))
evalStep :: Expression ->  Expression
evalStep (Val x)=  (Val x)
evalStep (Add x y)
   = case x of
       (Val a) -> case y of
                    (Val b) -> Val (a+b)
                    left -> Add x (evalStep y)
       right -> Add y(evalStep x)

evaluate :: Expression -> Expression
-- Base case
evaluate (Val a) = Val a

-- Recursive case
evaluate e = do
             putStrLn "Evaluating one more step"
             e' <- return (evalStep e)
             putStrLn ("Result is "++(show e'))
             putStrLn "Do another step (y/n)? :"
             c <- getChar
             if (c=='y') then
                evaluate e'
            else
               putStrLn "OK, finished"

Its suppose to print out the first step then ask you if you want the next
step all the way to the end
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
http://www.haskell.org/pipermail/beginners/attachments/20100125/05480709/attachment.html

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

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


End of Beginners Digest, Vol 19, Issue 25
*****************************************

Reply via email to