1

I have a basic problem, after if .. then I can not have more than one function, why?

check [] _ _ = []
check (x:xs) limit counter = if (x> head xs && counter < limit)
                              then incr counter -- I want here add another action 
                              else if ( x < head xs )
                                   then check xs limit counter
                                   else  incr x

main = do 
  print $ check [4,3,5,6] 1 0
  --- The answer I aim is : [3,4,5,6]

The goal of the check is to find whether each element is bigger than the next one or not, if yes then increase counter and do another action like swap their places, and there is a limit for this action, like here is just 1 time, means just 1 times it can do that action not more.

4

2 回答 2

3

您可以改用警卫:

check [] _ _ = []
check (x:xs) limit counter
             | x> head xs && counter < limit = incr counter
             | x < head xs                   = check xs limit counter
             | otherwise                     = incr x

您还可以使用caseMultyIf扩展

相反actionincr counter你可以写check xs limit (counter + 1)

关于交换,你可以试试

 ...  
| x> head xs && counter < limit = check (head xs : x : tail xs) limit (counter + 1)

我明白了,你还需要特殊情况head [] = error,所以你应该把你的功能划分为check (x:y:xs) ..and check [x]

所以,check (x:y:xs) ..如果我们可以重写

 ...  
| x> y && counter < limit = check (y : x : xs) limit (counter + 1)

当你这样做时,你已经发现我们有空列表作为结果。但是你想保存修改列表

所以,尝试添加更改检查功能

check' xs = reverse . check ([], xs) 0

check ( modXs, []) _ _  = modXs
check ( modXs, [x]) _ _ = x : modXs
check ( modXs, (x:y:xs)) counter limit = ...

要点 在函数内部没有“静态局部变量”,但在大多数情况下,递归是受欢迎的。如果确实需要使用“静态局部变量”,可以使用“内容中的数据”:monads, like IO, IORefof pure, likeState

于 2013-10-11T18:09:04.303 回答
1

关于您的第二次实施check

check ( modXs, []) _ _  = modXs
check ( modXs, [x]) _ _ = x : modXs
check ( modXs, (x1:x2:xs)) counter limit 
    | x1 > x2 && counter > limit =  x2:check (x1 : xs)  (incr counter) limit
    | otherwise = x1 : check (x2 : xs) counter limit 

你快到了,但它的类型错误,因为第一个参数check是一对,而在递归定义中你提供了一个列表。

于 2013-10-12T15:58:31.700 回答