[英]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.