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: Critique my program (Daniel Fischer)
2. Re: prefix instead of infix (Daniel Fischer)
3. Re: prefix instead of infix (Stephen Tetley)
4. Re: Randomness woes ( G?khan San)
5. Re: Randomness woes (Stephen Blackheath [to Haskell-Beginners])
6. Re: Critique my program (David Frey)
7. Understanding Monadic I/O (Markus B?hm)
8. Re: Randomness woes (Erlend Hamberg)
----------------------------------------------------------------------
Message: 1
Date: Sun, 10 Jan 2010 21:33:18 +0100
From: Daniel Fischer <[email protected]>
Subject: Re: [Haskell-beginners] Critique my program
To: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="iso-8859-1"
Am Sonntag 10 Januar 2010 20:44:38 schrieb David Frey:
> A couple of months ago, I was tutoring my cousin in an introductory
> computer science class. We talked about his assignment in which he had
> to implement a subset of the Battleship board game using Java.
>
> I decided it would be fun for me to try to complete the assignment in
> Haskell. I forgot about the project for a while, but I picked it up and
> finished it today.
>
> I have put the code on BitBucket (a Mercurial based code hosting site
> for those who don't know) at this location:
> http://bitbucket.org/dfrey/battleship/
>
> I am hoping that some people from this list could review my code. I'm
> not very concerned with correctness. I'm more interested in how my code
> can be clarified through use of existing functions or standard Haskell
> idioms.
I prefer to have e.g.
data BoardLocation
= BoardLocation
{ locationRow :: Int
, locationCol :: Int
}
deriving (Show, Eq)
but that's a matter of taste.
One thing that I dislike is
unsignedInteger = many1 digit >>= \x -> return $ read x
better is
unsignedInteger = many1 digit >>= return . read
, but
m >>= return . f
isn't good, that should be
fmap f m
or
liftM f m
, so I'd recommend
unsignedInteger = fmap read (many1 digit)
or, using Control.Applicative,
unsignedInteger = read <$> many1 digit
signedInteger could be
signedInteger = do
signFun <- option id (char '-' >> return negate)
fmap signFun unsignedInteger
it might be good to be more lenient with the format and allow more than one
space between items (and trailing whitespace for user input).
allPairs (x:xs) = [(x,y) | y <- xs] ++ allPairs xs
>
> If you don't have Mercurial installed or don't want to clone the
> repository, you can browse the source here:
> http://bitbucket.org/dfrey/battleship/src/
>
> The original PDF from my cousin's assignment can be viewed here:
> http://bitbucket.org/dfrey/battleship/raw/81a01574f164/Assn4.pdf
>
> Feel free to submit your comments in any format. Patches, written
> comments, complete re-writes of the program, etc. are all welcome.
>
> Thanks,
> David Frey
------------------------------
Message: 2
Date: Sun, 10 Jan 2010 21:46:20 +0100
From: Daniel Fischer <[email protected]>
Subject: Re: [Haskell-beginners] prefix instead of infix
To: John Moore <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="utf-8"
Am Sunday 10 January 2010 21:24:40 schrieben Sie:
> Hi Daniel,
> I want to add a let expression to the program so as I can
> enter let x = y in z or something to that effect. I was going along the
> lines of using prefix as I cant use infix so I thought I would make it
> easier by using prefix notation. Probably a bad idea.
>
> John
If you want only one binding per let, I think
letExpr = do
keyword "let" -- implementation of keyword is left as an exercise
bind <- variable -- binding patterns like (x,y) is left for later
-- maybe check for "=" ?
rhs <- expression
keyword "in"
use <- expression
return (Let bind rhs use)
expression = letExpr <|> expr
factor = between (char '(') (char ')') expression <|> atom
atom = variable <|> number
would work (untested).
>
> On Sun, Jan 10, 2010 at 8:14 PM, Daniel Fischer
<[email protected]>wrote:
> > Am Sonntag 10 Januar 2010 20:33:40 schrieb John Moore:
> > > Hi,
> > > Can anyone explain how to turn the code from infix to Prefix. I
> > > want to include a let statement below. I not sure of how prefix
> > > works.
> >
> > Can you elaborate? I don't understand what it is you want to do.
> > Do you want to parse expressions in prefix notation (aka Polish
> > notation), such as +(3,4) (or, more Lispy, (+ 3 4))?
> > That'd be simple, but you wouldn't use buldExpressionParser for that
> > (in Polish notation, neither associativity nor precedence have a
> > meaning). Or do you want to add a parser for let-expressions to expr?
> >
> > > expr :: Parser Expr
> > > expr = buildExpressionParser table factor
> > > <?> "expression"
> > > table :: [[Operator Char st Expr]]
> > > table = [[op "*" Mul AssocLeft, op "/" Div AssocLeft]
> > > ,[op "+" Add AssocLeft, op "-" Sub AssocLeft]
> > > ]
> > > where
> > > op s f assoc
> > > = Infix (do{ string s; return f}) assoc
> > > factor :: Parser Expr
> > > factor = do{ char '('
> > > ; x <- expr
> > > ; char ')'
> > > ; return x
> > > }
> > > <|> number
> > > <?> "simple expression"
> > > number :: Parser Expr
> > > number = do{ ds <- many1 alphaNum
> > > ; return (Val $ read ds)
> > > }
> > >
> > > John
------------------------------
Message: 3
Date: Sun, 10 Jan 2010 20:52:56 +0000
From: Stephen Tetley <[email protected]>
Subject: Re: [Haskell-beginners] prefix instead of infix
To: John Moore <[email protected]>
Cc: [email protected]
Message-ID:
<[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
2010/1/10 John Moore <[email protected]>:
> Can anyone explain how to turn the code from infix to Prefix. I want to
> include a let statement below. I not sure of how prefix works.
>
Hi John
For a let expression you want to extend the 'topmost' expr parser to
include a case for "let" rather than try to accommodate it in the
'table' parser.
Putting a extra 'in' keyword probably makes parsing simpler, i.e. "
let var = ... in ...", should you want to add other syntax later
(especially function application).
Once you start adding keywords you then start to be concerned about
whitespace and lexing - Parsec has a couple of modules for this -
Language and Token. In a nutshell where the parser previously used the
'string' parser it should use the 'symbol' parser as symbol consumes
trailing whitespace. The Token module is usually imported qualified
and you then redefine the functions you want to use with a particular
language definition (in this case emptyDef) - the bottom of the file
shows this idiom for the 'symbol', 'identifier' and 'integer' parsers.
Best wishes
Stephen
module ExprSyn where
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
-- new imports ...
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language (emptyDef)
runExpr :: String -> IO ()
runExpr str = case runParser expr () "nofile" str of
Left err -> putStrLn "Error:" >> print err
Right val -> print val
demo1 = runExpr "1+1"
demo2 = runExpr "let x = 5+3 in x+7"
type Variable = String
data Expr = Mul Expr Expr
| Div Expr Expr
| Add Expr Expr
| Sub Expr Expr
| Val Integer
| Var String
| LetIn Variable Expr Expr
deriving (Eq,Show)
expr :: Parser Expr
expr = letInExpr
<|> buildExpressionParser table factor
<?> "expression"
letInExpr :: Parser Expr
letInExpr = do { symbol "let"
; var <- identifier
; symbol "="
; bind <- expr
; symbol "in"
; body <- expr
; return (LetIn var bind body)
}
table :: [[Operator Char st Expr]]
table = [[op "*" Mul AssocLeft, op "/" Div AssocLeft]
,[op "+" Add AssocLeft, op "-" Sub AssocLeft]
]
where
op s f assoc
= Infix (do{ symbol s; return f}) assoc
factor :: Parser Expr
factor = do{ char '('
; x <- expr
; char ')'
; return x
}
<|> number
<|> variable
<?> "simple expression"
number :: Parser Expr
number = do{ n <- integer
; return (Val $ fromIntegral n)
}
<?> "number"
variable :: Parser Expr
variable = do{ cs <- identifier
; return (Var cs)
}
<?> "number"
---
-- Bit of work to get 'symbol' and 'identifier' parsers working
-- both are useful as they consume trailing white space
-- Lexical analysis
baseLex :: P.TokenParser st
baseLex = P.makeTokenParser emptyDef
symbol :: String -> CharParser st String
symbol = P.symbol baseLex
identifier :: CharParser st String
identifier = P.identifier baseLex
integer :: CharParser st Integer
integer = P.integer baseLex
------------------------------
Message: 4
Date: Sun, 10 Jan 2010 21:58:02 +0100
From: [email protected] ( G?khan San)
Subject: Re: [Haskell-beginners] Randomness woes
To: Erlend Hamberg <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=utf-8
Erlend Hamberg <[email protected]> writes:
> g <- getSplit
> let genome' = evalRand (mutate genome) g
>
> Handling the random generator explicitly like this feels a bit ugly. Or is
> this okay?
I was working on a very similar problem and I used 'split' of RandomGen
all the way down. It behaved well as far as I can tell, and if I recall
correctly, 'split' was faster than 'next' for StdGen.
So, I'd also appreciate any comment on the elegance issue myself. :-)
Though, I didn't quite get why you are explicitly calling 'evalRand'
instead of utilizing MonadRandom.
Here's an example:
> makePopulation :: (RandomGen g) => [(Genome, Fitness)] -> Rand g [Genome]
> makePopulation chms = do
> g <- getSplit
> return $ makePopulation' chms g []
> where size = length chms
> makePopulation' c g' a =
> if length a == size
> -- if we have âsizeâ members, we are done
> then a
> -- if not, find two new parents and append a child
> else makePopulation' c g' newPop
> where parent1 = evalRand (rouletteSelect chms) g'
> parent2 = evalRand (rouletteSelect chms) g'
> c1 = evalRand (reproduce (parent1,
> parent2) mutationRate) g'
> newPop = c1:a
Here, you're generating both parents using the same random generator,
hence, parents are always identical. Here's a variation that works
within MonadRandom:
> makePopulation :: (RandomGen g) => [(Genome, Fitness)] -> Rand g [Genome]
> makePopulation chms = makePopulation' []
> where size = length chms
> makePopulation' a =
> if length a == size
> -- if we have âsizeâ members, we are done
> then return a
> -- if not, find two new parents and append a child
> else do parent1 <- rouletteSelect chms
> parent2 <- rouletteSelect chms
> c1 <- reproduce (parent1, parent2) mutationRate
> let newPop = c1:a
> makePopulation' newPop
I didn't check for bugs in the algorithm but now both parents and the
offspring are generated independently, and resulting fitness values
won't be identical.
I think the idea is that you should be able to reduce the number of
'evalRand's in your module to one.
--
Gökhan San
------------------------------
Message: 5
Date: Mon, 11 Jan 2010 10:03:46 +1300
From: "Stephen Blackheath [to Haskell-Beginners]"
<[email protected]>
Subject: Re: [Haskell-beginners] Randomness woes
To: Erlend Hamberg <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset=UTF-8
Erlend - see below...
Erlend Hamberg wrote:
> ...
> I have two concerns about my architecture. The first one is that I have
> several âlayersâ of randomness: The main function will call
> makePopulation
> which in turn will call rouletteSelect and reproduce. The latter will then
> call mutate, which also involves randomness. As can be seen above, I have
> rewritten mutate to take a list of booleans so that I can use getRandomRs in
> reproduce instead of having to have yet another layer of
>
> g <- getSplit
> let genome' = evalRand (mutate genome) g
>
> Handling the random generator explicitly like this feels a bit ugly. Or is
> this okay?
If you replace the code above with just
mutate genome
then it will pass the random number generator 'through' mutate and on
completion the RNG in the calling context will be changed to what
'mutate' returned. Since you're not using multiple threads, this should
be correct for your application, but it's not quite equivalent to your
code, because you're not actually splitting the RNG. If you really need
to split it, you could write yourself a helper function like this:
splitting :: RandomGen g => Rand g a -> Rand g a
splitting code = do
g <- getSplit
return $ evalRand code g
Then say
splitting $ mutate genome
> Calling getSplit and then evalRand recursively is what I do in
> makePopulation,
> to make a new population. I would greatly appreciate comments on how this
> âshouldâ be done. I realise that I could just get a list of random
> numbers in
> makePopulation and then use this as a source of randomness for the called
> functions, but I fear that this would just lead to inelegant code managing
> (chunks of) this list.
Gokhan San answered this better than I was going to.
Steve
------------------------------
Message: 6
Date: Sun, 10 Jan 2010 16:12:59 -0800
From: David Frey <[email protected]>
Subject: Re: [Haskell-beginners] Critique my program
To: [email protected]
Message-ID: <[email protected]>
Content-Type: Text/Plain; charset="us-ascii"
I have received a couple of responses off list so far.
One came from Erlend Hamberg. He suggested that I run hlint as a first step.
The other response came from Daniel Fischer. He provided more concise
versions of some of the functions that I wrote.
I have made changes based on both responses and committed it to
http://bitbucket.org/dfrey/battleship/
Thanks for the suggestions.
David
On January 10, 2010 11:44:38 am David Frey wrote:
> A couple of months ago, I was tutoring my cousin in an introductory
> computer science class. We talked about his assignment in which he had to
> implement a subset of the Battleship board game using Java.
>
> I decided it would be fun for me to try to complete the assignment in
> Haskell. I forgot about the project for a while, but I picked it up and
> finished it today.
>
> I have put the code on BitBucket (a Mercurial based code hosting site for
> those who don't know) at this location:
> http://bitbucket.org/dfrey/battleship/
>
> I am hoping that some people from this list could review my code. I'm not
> very concerned with correctness. I'm more interested in how my code can be
> clarified through use of existing functions or standard Haskell idioms.
>
> If you don't have Mercurial installed or don't want to clone the
> repository, you can browse the source here:
> http://bitbucket.org/dfrey/battleship/src/
>
> The original PDF from my cousin's assignment can be viewed here:
> http://bitbucket.org/dfrey/battleship/raw/81a01574f164/Assn4.pdf
>
> Feel free to submit your comments in any format. Patches, written
> comments, complete re-writes of the program, etc. are all welcome.
>
> Thanks,
> David Frey
------------------------------
Message: 7
Date: Mon, 11 Jan 2010 14:57:21 +0100
From: Markus B?hm <[email protected]>
Subject: [Haskell-beginners] Understanding Monadic I/O
To: [email protected]
Message-ID:
<[email protected]>
Content-Type: text/plain; charset=ISO-8859-1
Hi, I'd like to understand in principle, how monadic I/O actions and
combinators (>>=) are translated into imperative C--, to be executed
sequentially.
Does sequencing of IO actions mean nesting of C-- functions and
passing values/state via additional function parameters?
Is there any material with examples available?
P.S.: Just to understand the magic better. I need it.
BR
-- Markus
------------------------------
Message: 8
Date: Mon, 11 Jan 2010 18:25:12 +0100
From: Erlend Hamberg <[email protected]>
Subject: Re: [Haskell-beginners] Randomness woes
To: G?khan San <[email protected]>
Cc: [email protected]
Message-ID: <[email protected]>
Content-Type: text/plain; charset="utf-8"
On Sunday 10. January 2010 21.58.02 Gökhan San wrote:
> Though, I didn't quite get why you are explicitly calling 'evalRand'
> instead of utilizing MonadRandom.
Because of a misunderstanding on my part. I changed all the code as you
suggested and now it's much nicer.
> Here, you're generating both parents using the same random generator,
> hence, parents are always identical.
D'oh. That explains it. Thanks! :)
--
Erlend Hamberg
âEverything will be ok in the end. If its not ok, its not the end.â
GPG/PGP: 0xAD3BCF19
45C3 E2E7 86CA ADB7 8DAD 51E7 3A1A F085 AD3B CF19
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part.
Url :
http://www.haskell.org/pipermail/beginners/attachments/20100111/4304f2d4/attachment.bin
------------------------------
_______________________________________________
Beginners mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/beginners
End of Beginners Digest, Vol 19, Issue 7
****************************************