I’ve been working on adding a counter to variables in a given expression and have the following test case:
prop_add1 = add (And (Var "a") (And (Var "b") (Var "a"))) ==
And (Var "a1") (And (Var "b2") (Var "a1"))
I have been using Pattern Matching and Recursion to try and find a solution. Although I have come a little stuck, I have tried adding the original variables to a list and then using the list to determine the variable name to be output but I couldn’t figure out how to correctly implement it and my output just adds a 1 to the end of all variables.
I’m wondering is there a better/easier solution to this?
My Attempt so far:
add :: Expr -> Expr
add T = T
add (Var x) = Var (x ++ show (check2(check x)))
add (And e1 e2) = And (add e1) (add e2)
add (Not e1) = Not (add e1)
check :: Variable -> [Variable]
check p = [p]
check2 :: [Variable] -> Int
check2 p = length (union p p)
You need to keep an environment mapping variable names to numbers. Something like
I hope I’ve left enough for you to fill in.
Update:
In your attempt, you don’t keep track of which variables you have already seen, so every variable seems to be the first, and every time a ‘1’ is appended. Numbering items is a stateful computation, you must have a record of which variables have been seen so far to assign previously seen variables the old number and know which number to assign the next not-yet-seen variable. So you must carry that record around in the worker. If you already know about the
Monadclass and how to use that, you can implicitly carry it around using theStatemonad, otherwise you have to carry it around explicitly. Thenaddbecomes a wrapper that calls the worker with an initially empty state (before the numbering/renaming starts, no variable has yet been seen). The worker then looks at the subexpressions of the given expression (if any) and renames variables and updates the state when a new variable is encountered.So in the sketch above, we have
since we cannot mutate the state, we have to return the new state along with the renamed expression. Now you have to define what the result shall be for each type of expression,
The
Tcase of course does no renaming and doesn’t update the environment. AVarhas either been seen before, in which case the environment remains unchanged, or not, in which case it is added to the environment. ANot ehas the same influence on the environment ase, and anAnd e1 e2has the combined effects of firste1thene2on the environment.