[Haskell-cafe] Arithmetic expressions with random operators
Francesco Ariis
fa-ml at ariis.it
Thu Jun 8 13:52:18 UTC 2017
On Thu, Jun 08, 2017 at 04:03:55PM +0300, Mahmoud Murad wrote:
> I have the following problem, I want to randomly generate arithmetic
> expressions based on a number, for example:
> if I have n = 3, then the expression must have 3 operators like this
> (4)*(((3+5)-2)).
Hello Mahmoud,
probably not the most flexible and posh solution, but datatypes
would do.
data Exp = EInt Integer
| Sum Exp Exp
| Diff Exp Exp
| Mult Exp Exp
and then of course you want to write
evaluate :: Exp -> Integer
and
write :: Exp -> String
-- maybe instance Show Exp where
Once you do that, picking Exp constructors at random should not be
difficult.
There are other ways to write a DSL like this (using GADTs, tagless
final style, etc.), each of those expands on/solves a specific problem
(extensibility, etc.); but there is no benefit in complicating your code
if you don't need it.
Does that help?
-F
More information about the Haskell-Cafe
mailing list