gpt4 book ai didi

Haskell 函数返回空列表

转载 作者:行者123 更新时间:2023-12-02 16:35:27 26 4
gpt4 key购买 nike

我确实是 Haskell 的绝对新手,所以我完全不知道如何调试我编写的一些函数。当我调用 shuntingYard ["3+4"] 时,我会返回 [],而我想要返回 [34+]。任何和所有的帮助将非常非常感谢。

import Char

isOperator :: Char -> Bool
isOperator x = elem x ['+','-','*','/','%','^','!','=','<','>']

associativityOf :: Char -> String
associativityOf x = if elem x ['+','-','*','/','%']
then "Left"
else "Right"

precedenceOf :: Char -> Int
precedenceOf x
| elem x "=<>" = 1
| elem x "+-" = 2
| elem x "*/%" = 3
| elem x "^!" = 4
| otherwise = 0

operatorActions :: [[Char]] -> [[Char]] -> [[Char]]
operatorActions stmt stack
| ( tokenAssoc == "Left" && tokenPrecedence <= stackPrecedence ) ||
( tokenAssoc == "Right" && tokenPrecedence < stackPrecedence ) =
[stackOper] : _shuntingYard stmt (tail stack)
| otherwise = _shuntingYard (tail stmt) ((head stmt) : stack)
where tokenAssoc = associativityOf (head (head stmt))
tokenPrecedence = precedenceOf (head (head stmt))
stackOper = if (not (null stack))
then (head (head stack))
else '='
stackPrecedence = precedenceOf stackOper

stackOperations :: [[Char]] -> [[Char]]
stackOperations stack
| ((not (null stack)) && (head (head stack)) == '(') =
error "Unbalanced parens."
| null stack = []
| otherwise = (head stack) : _shuntingYard [] (tail stack)

_shuntingYard :: [[Char]] -> [[Char]] -> [[Char]]
_shuntingYard stmt stack
| null stmt = stackOperations stack
| all isDigit (head stmt) = (head stmt) : _shuntingYard (tail stmt) stack
| isOperator (head (head stmt)) = operatorActions stmt stack
| (head (head stmt)) == '('=
_shuntingYard (tail stmt) ((head stmt) : stack)
| (head (head stmt)) == ')' = if (head (head stack)) == '('
then _shuntingYard (tail stmt) (tail stack)
else (head stack) : _shuntingYard stmt (tail stack)
| otherwise = _shuntingYard (tail stmt) stack

shuntingYard :: [[Char]] -> [[Char]]
shuntingYard stmt = _shuntingYard stmt []

最佳答案

作为一种通用的调试技术,您可以使用 Debug.Trace 模块来找出正在调用哪些函数以及它们的输入是什么。在每个步骤之后查看算法的状态。

import Debug.Trace

-- Show arguments each time _shuntingYard is called
_shuntingYard :: [[Char]] -> [[Char]] -> [[Char]]
_shuntingYard stmt stack = traceShow (stmt, stack) $ __shuntingYard stmt stack

__shuntingYard stmt stack
| null stmt = stackOperations stack
{- etcetera -}

打印:

(["3+4"],[])
([],[])

嗯,第一次通话后你就失去了一切。看看 __shuntingYard 中的 guard ,似乎“否则”案件被传唤了。

也许您想调用shuntingYard ["3", "+", "4"]

关于Haskell 函数返回空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5370678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com