[英]Using functions inside list comprehensions, Haskell?
我們可以放置函數以確定列表理解的條件嗎? 這是我要實現的代碼:
mQsort :: [String] -> [F.Record] -> [F.Record]
mQsort [] _ = []
mQsort c@(col:cond:cs) l@(x:xs) = (mQsort c small) ++ mid ++ (mQsort c large)
where
small = [y | y<-xs, (qGetStr col y) (qGetCond cond) (qGetStr col x)]
mid = mQsort cs [y | y<-l, (qGetStr col y) == (qGetStr col x)]
large = [y | y<-xs, (qGetStr col y) (qGetCond' cond) (qGetStr col x)]
qGetStr :: String -> F.Record -> String
qGetStr col r | U.isClub col = F.club r
| U.isMap col = F.mapName r
| U.isTown col = F.nearestTown r
| U.isTerrain col = F.terrain r
| U.isGrade col =F.mapGrade r
| U.isSW col = F.gridRefOfSWCorner r
| U.isNE col = F.gridRefOfNECorner r
| U.isCompleted col = F.expectedCompletionDate r
| U.isSize col = F.sizeSqKm r
| otherwise = ""
qGetCond "ascending" = (<)
qGetCond "decending" = (>)
qGetCond' "ascending" = (>)
qGetCond' "decending" = (<)
我收到一條錯誤消息,指出函數qGetStr被應用於4個參數而不是2個。
同樣,qGetCond-這是返回運算符的正確語法。 由於編譯錯誤,我不得不將運算符放在方括號中,但是我感覺這是不正確的
更換
small = [y | y<-xs, (qGetStr col y) (qGetCond cond) (qGetStr col x)]
與
small = [y | y<-xs, (qGetCond cond) (qGetStr col y) (qGetStr col x)]
同樣對於large
。
原因與用於在qGetCond
返回運算符的語法的原因相同。 運算符實際上只是一個函數。
foo < bar
與(<) foo bar
foo `fire` bar
與fire foo bar
相同 因此,您必須將“運算符”移動到列表理解中表達式的開頭。 (nb通常是正確的,尤其與列表理解無關。)
編輯:擴展克里斯·庫克萊維茨的觀點:
反引號僅適用於單個標識符。 所以foo `fire` bar
是有效的語法,但一些復雜的東西foo `fire forcefully` bar
或foo `(fire forcefully)` bar
是一個語法錯誤。
圓括號運算符更靈活。 這些表達式的求值均相同:
foo < bar
(<) foo bar
(foo <) bar
(< bar) foo
最后兩種形式稱為運算符部分。 當將一個函數傳遞給另一個函數(例如map (+1) listOfIntegers
時,它們很有用。 語法有一些細微之處:
(quux foo <) -- function calls are fine (baz + foo <) -- syntax error because of the extra operator... ((baz + foo) <) -- ...but this is ok (-3) -- `-` is a special case: this is a numeric literal, -- not a function that subtracts three (subtract 3) -- is a function that subtracts three
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.