我似乎无法成功地用 Fay 对字符串进行排序。我意识到这与 Fay 不支持类型类的事实有关,但如果这不起作用,那似乎真的很痛苦......
import Prelude
main :: Fay ()
main = print $ sort ["a", "c", "b"]
输出是:
fay: ghc:
Test.hs:4:16:
No instance for (Ord [Char])
arising from a use of `sort'
Possible fix: add an instance declaration for (Ord [Char])
In the second argument of `($)', namely `sort ["a", "c", "b"]'
In the expression: print $ sort ["a", "c", "b"]
In an equation for `main': main = print $ sort ["a", "c", "b"]
如果我理解正确,我无法自己定义类型类的实例,因为 Fay 不支持类型类(另外我猜如果 Fay 开发人员一开始就会这样做)。那么是否有解决方法,或者我必须使用 JS FFI 来进行字符串排序?
编辑: Jan Christiansen 的答案似乎是正确的:我可以使用“sortBy”进行排序,这乍一看似乎是正确的:
import Prelude
main :: Fay ()
main = print $ sortBy strComp ["a", "c", "b"]
strComp :: String -> String -> Ordering
strComp (_:_) [] = GT
strComp [] (_:_) = LT
strComp [] [] = EQ
strComp (x:xs) (y:ys)
| x < y = LT
| x > y = GT
| otherwise = strComp xs ys
编译:
fay --html-wrapper Sort.hs