2017-04-15 59 views
2

我有點新的哈斯克爾,但我一直在這個問題沒有運氣了幾個小時。哈斯克爾錯誤:變量不在範圍內

我想實現類似於過濾器的東西,除了謂詞和列表被傳遞給一個函數,並且它返回兩個列表的一個元組,一個由謂詞過濾而另一個不是。

divideList :: (a -> Bool) -> [a] -> ([a],[a]) 
divideList p xs = (f, nf) where 
f = doFilter p xs 
nf = doFilter (not . p) xs 

doFilter :: (a -> Bool) -> [a] -> [a] 
doFilter _ [] = [] 
doFilter p (x:xs) = [x | p x] ++ doFilter p xs 

第二個函數doFilter正常工作。它將過濾器應用到列表中並吐出適當的列表。 (即如果我只是用doFilter (>3) [1,2,3,4,5,6]它將正常工作)

我的問題是與第一功能。當我使用divideList (>3) [1,2,3,4,5,6]時,我得到一些Variable not in scope錯誤。這些錯誤如下:

AddListOperations.hs:20:23: error: 
    Variable not in scope: p :: a -> Bool 

AddListOperations.hs:20:25: error: Variable not in scope: xs :: [a] 

AddListOperations.hs:21:31: error: 
    Variable not in scope: p :: a -> Bool 

AddListOperations.hs:21:34: error: Variable not in scope: xs :: [a] 

就像我說的,我只瞎搞哈斯克爾幾天,所以讓我知道如果我離開了任何重要信息。

+1

你需要縮進'F = ...'和'NF = ...'否則沒有辦法知道他們被附加到'divideList'。 – Alec

+0

我不能相信這是所有花了......太感謝你了 –

+0

BTW,[Hoogle會告訴你(https://www.haskell.org/hoogle/?hoogle=%28a+-%3E+ Bool%29 +%3E +%5Ba%5D + - %3E +%28%5Ba%5D%2C%5Ba%5D%29)'partition'是您想要的功能。 – leftaroundabout

回答

1

縮進兩個fnf

divideList :: (a -> Bool) -> [a] -> ([a],[a]) 
divideList p xs = (f, nf) where 
    f = doFilter p xs 
    nf = doFilter (not . p) xs 

畢竟,在那裏你會塊where停止?

順便說一句,divideListpartitionData.List

+0

謝謝,我只是意識到我所需要的只是一些縮進。根據謂詞(la過濾器)劃分單獨的列表嗎? –

+1

[是](https://hackage.haskell.org/package/base-4.9.1.0/docs/Data-List.html#v:partition) – Zeta

0

感謝亞歷克,我發現,所有我需要做的是縮進語句下面where

divideList :: (a -> Bool) -> [a] -> ([a],[a]) 
divideList p xs = (f, nf) where 
    f = doFilter p xs 
    nf = doFilter (not . p) xs