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]
answerListasanswerList = createOptions <$> [0..3] <*> [0..3] <*> [0..3]4+4+(4*4)and(4+4+4)*4(and others...4+(4+4)*4and 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.