Sha*_*ane 1 haskell list-comprehension
我们可以放置函数来确定列表推导的条件.这是我试图实现的代码:
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" = (<)
Run Code Online (Sandbox Code Playgroud)
我得到一个错误,说明函数qGetStr应用于4个参数而不是2.
此外,qGetCond - 这是返回运算符的正确语法.由于编译错误,我不得不将操作符放在括号中,但我觉得这是不正确的
更换
small = [y | y<-xs, (qGetStr col y) (qGetCond cond) (qGetStr col x)]
Run Code Online (Sandbox Code Playgroud)
同
small = [y | y<-xs, (qGetCond cond) (qGetStr col y) (qGetStr col x)]
Run Code Online (Sandbox Code Playgroud)
同样的large.
原因与您用于返回运算符的语法的原因相同qGetCond.操作员真的只是一个功能.
foo < bar 是相同的 (<) foo barfoo `fire` bar 是相同的 fire foo bar因此,您必须将"运算符"移动到列表推导中表达式的开头.(总的来说这是正确的,特别是与列表推导无关.)
编辑:扩展Chris Kuklewicz的观点:
反引号只能处理单个标识符.所以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
Run Code Online (Sandbox Code Playgroud)