PaRaDoX
PaRaDoX

Reputation: 23

join function and type issues haskell

I have 2 lists Expressions and bindings (id = Expr), and trying to replace each expression with its equivalent from the bindings list in a new list called newE, where Expression = id .. Initially, I have only one expression:

eq (div (add 2 7) (sub 5 2)) 3

I want to replace each identifier in this expression with its equivalent from the bindings list, so I tried to split this expression into a list of strings and removed brackets, to separate each identifier ..

This is how I tried to implement it:

newE = [\x -> getExp(b) | x <- eStr, b <- bs, x == getId(b)]
                where es = getExpressions (prog)
                      bs = getBindings (prog)
                      -- Extracting expression into a list of strings 
                      -- and removing brackets
                      eStr = map (delete ')')(map (delete ')') 
                             (map (delete '(') (split " " (show es))))
newE' = join " " newE

Is this correct?

Now I'm getting errors that newE returns [t0 -> Expr] while it's supposed to return Expr only, why is that?

and the join function is expecting a [Char] .. while its type in the Data.List.Utils documentation is:

join :: [a] -> [[a]] -> [a]

so, isn't it supposed to accept any type not just list of characters? or did it get confused with a 'join' from another library? I searched the libraries I've imported, but they don't have a join.

Any help to resolve these errors and modify the code to do what it's supposed to do?

Thank you

Upvotes: 0

Views: 166

Answers (2)

ErikR
ErikR

Reputation: 52039

Since you asked, here is a sketch of the conventional approach:

  1. Convert the string expression into a Expr value, e.g.

    add 2 7 -> App (App (Var "add") (Var "2")) (Var "7")

  2. Write a function lookupBinding to lookup a binding for a Symbol:

    lookupBinding :: [Binding] -> Symbol -> Maybe Expr

  3. Write a substitute function to substitute binding definitions into an expression:

    substitute :: [Binding] -> Expr -> Expr

It will go something like this:

substitute bindings (App e1 e2) = App e1' e2'
  where e1' = substitute bindings e1
        e2' = substitute bindings e2

substitute bindings (Var sym) = ... lookupBinding sym ...
substitute bindings (Lam sym exp) = ... substitute bindings' exp ...

Upvotes: 1

Chuck
Chuck

Reputation: 237030

Your list comprehension body returns the function \x -> getExp b. That's why the compiler says it's returning a function type.

Upvotes: 0

Related Questions