[Haskell-cafe] Arithmetic expressions with random operators

Mahmoud Murad mahmoudmurad92 at gmail.com
Thu Jun 8 14:34:52 UTC 2017


Thanks Francesco, I will try it

8 Haz 2017 16:55 tarihinde "Francesco Ariis" <fa-ml at ariis.it> yazd─▒:

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
_______________________________________________
Haskell-Cafe mailing list
To (un)subscribe, modify options or view archives go to:
http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
Only members subscribed via the mailman list are allowed to post.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20170608/8a0e35fb/attachment.html>


More information about the Haskell-Cafe mailing list