Haskell中的递归函数和停止条件

时间:2013-03-31 12:14:16

标签: haskell recursion

我正在实现一个递归函数,我希望停止条件是(2 * scope)这是函数的参数

sortByManhattanDistance agent (2*scope) scope xs sortedNearFoodList = sortedNearFoodList

sortByManhattanDistance agent n scope xs sortedNearFoodList = sortByManhattanDistance agent (n+1) scope xs (sorted ++ sortedNearFoodList) 
where sorted=compareManhattanDistance xs agent n
抱抱抱怨:Syntax error in declaration (unexpected symbol "*") 这是否意味着我不能在参数上使用某些功能?

提前致谢

1 个答案:

答案 0 :(得分:5)

不,你不能在等式的左边使用函数或运算符。

执行所需操作的正确方法是使用guards

sortByManhattanDistance agent n scope xs sortedNearFoodList
    | n == 2 * scope = sortedNearFoodList
    | otherwise      = sortByManhattanDistance agent (n+1) scope xs
                                            (sorted ++ sortedNearFoodList) 
  where sorted = compareManhattanDistance xs agent n