功能参数不在函数体的范围内?

时间:2014-03-24 05:37:59

标签: haskell

我正在通过一些练习来学习一些Haskell(更好的)。

以下是我对BubbleSort的尝试:

bubbleSort :: [Integer] -> [Integer]
bubbleSort xs = let 
                  (state, bubbled) = bubble True xs
                in  
                  if not state
                  then bubbleSort bubbled
                  else bubbled
  where
    bubble :: Bool -> [Integer] -> (Bool, [Integer])
    bubble changed [] = (changed, []) 
    bubble changed [x] = (changed, [a])
    bubble changed (a:b:as) | compare a b == GT = (fst bubble False (a:as), b:(snd bubble False (a:as)))
                            | otherwise = (fst bubble (changed && True) (b:as), a:(snd bubble (changed && True) (b:as))) 

这在最后一行(在else子句中)出错:Not in scope: 'a'

老实说,我不确定我是否只是非常疲惫,或者我错过了一些非常基本的东西,但据我所知,a应该在范围内,因为它是作为(a)的一部分传递的:b:as)模式? 这不正确吗?

1 个答案:

答案 0 :(得分:3)

您的otherwise案例没有问题,但不是这种情况:bubble changed [x] = (changed, [a]) ... a不在范围内。

import           Data.List       (sort)
import           Test.QuickCheck

main :: IO ()
main = verboseCheck isValidSort >> verboseCheck idempotent

isValidSort, idempotent :: [Integer] -> Bool
isValidSort xs = sort xs == bubbleSort xs
idempotent  xs = bubbleSort (bubbleSort xs) == bubbleSort xs

bubbleSort :: [Integer] -> [Integer]
bubbleSort xs = let (state, bubbled) = bubble True xs
                in if not state
                   then bubbleSort bubbled
                   else bubbled
  where
    bubble :: Bool -> [Integer] -> (Bool, [Integer])
    bubble changed [] = (changed, [])
    bubble changed [x] = (changed, [x])
    bubble changed (a:b:as) | compare a b == GT = (fst $ bubble False (a:as), b:(snd $ bubble False (a:as)))
                            | otherwise = (fst $ bubble (changed && True) (b:as), a:(snd $ bubble (changed && True) (b:as)))