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

nur*_*tey 1 recursion haskell

我正在实现一个递归函数,我希望停止条件为(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
Run Code Online (Sandbox Code Playgroud)

和拥抱抱怨:这Syntax error in declaration (unexpected symbol "*") 是否意味着我不能在参数上使用某些功能?

提前致谢

dav*_*420 5

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

做你想做的事的正确方法是使用警卫:

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
Run Code Online (Sandbox Code Playgroud)