I can't seem to succeed in sorting strings with Fay. I realize that it's connected to the fact that Fay doesn't support type classes, but that seems like a real pain if that doesn't work...
import Prelude
main :: Fay ()
main = print $ sort ["a", "c", "b"]
the output is:
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"]
I can't define the instance for the typeclass myself if I understand correctly, as Fay doesn't support typeclasses (plus I guess if it was possible the Fay developers would have done it to begin with). So is there a workaround, or must I do JS FFI to do string sorting?
EDIT: the answer from Jan Christiansen appears correct: I can sort using "sortBy", this appears correct at first sight:
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
To be compiled with:
fay --html-wrapper Sort.hs
I am no expert on fay but the Prelude of fay-base
defines a couple of instances of standard type classes, for example, an instance of Eq
for [a]
. However, it does not define an instance of Ord
for [a]
. As far as I know you cannot define an instance yourself. Therefore, you probably have to resort to sortBy
, which takes an additional function as argument. This function is used to compare two elements of the list, that is, in your case this function is used to compare two strings. You have to provide this function yourself but at least you do not have to use the javascript FFI.