0

So I'm doing some coding problem and in order to solve it I'm trying to create a list of all the possible answers and then I will see if that answer exists when asked to. However I am running into a problem with the function precedence of "o1", "o2", and "o3" - even though they represent expressions like *, div, +, - they all have the same precedence so when an option like 4 + 4 + 4 * 4 arises, the program answers with 48 instead of the correct answer, which is 24.

What I'm trying to ask is, are there any ways I can change the precedence of the functions "o1", "o2", and "o3", or make them reflect the operator's precedence?

The Code:

options :: [Int -> Int -> Int] options = [(+), (-), div, (*)] optionsStr = [" + 4", " - 4", " / 4", " * 4"] createOptions :: Int -> Int -> Int -> (Int, String) createOptions first second third = (key, value) where o1 = options !! first o2 = options !! second o3 = options !! third key = 4 `o1` 4 `o2` 4 `o3` 4 -- precedence issue is here value = "4" ++ (optionsStr !! first) ++ (optionsStr !! second) ++ (optionsStr !! third) answerList :: [(Int, String)] answerList = (concat . concat) $ map f [0..3] where f x = map (f' x) [0..3] f' x y = map (createOptions x y) [0..3] 
2
  • 2
    A bit of style advice: you can rewrite answerList as answerList = createOptions <$> [0..3] <*> [0..3] <*> [0..3] Commented Feb 1, 2021 at 6:34
  • 2
    Sounds like an XY problem to me. Presumably you want to consider both 4+4+(4*4) and (4+4+4)*4 (and others... 4+(4+4)*4 and more) as potential candidates. If so, you really just need to enumerate the trees with these operations at the internal nodes, and then evaluate the trees without consideration for precedence at all. We only use precedence and parentheses to get a convenient flat syntax for expressions, but the structured tree representation is what's really underlying an expression. Commented Feb 2, 2021 at 0:15

1 Answer 1

2

You can change the precedence of infix functions with fixity declarations:

infixl 6 `o1` infixl 6 `o2` infixl 7 `o3` 

See the haskell report

Sign up to request clarification or add additional context in comments.

1 Comment

Using infixl is the right way to get what he wants, but in his particular code, that doesn't work because the o1/o2/o3's are bound to different operations depending on the arguments of the function. He's probably better off setting this at the top level.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.