如何解决Haskell 中的函数优先级
所以我正在做一些coding problem,为了解决它,我正在尝试创建一个所有可能答案的列表,然后我会在被要求时查看该答案是否存在。但是,我遇到了“o1”、“o2”和“o3”的函数优先级问题——即使它们表示像*、div、+这样的表达式——它们都具有相同的优先级,所以当像4这样的选项时+ 4 + 4 * 4 出现,程序的答案是 48,而不是正确答案,即 24。
我想问的是,有什么方法可以改变函数“o1”、“o2”和“o3”的优先级,或者让它们反映运算符的优先级?
代码:
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]
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。