Thezi
Thezi

Reputation: 159

Function Precedence In Haskell

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]

Upvotes: 0

Views: 107

Answers (1)

414owen
414owen

Reputation: 801

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

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

See the haskell report

Upvotes: 2

Related Questions