Question

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
Was it helpful?

Solution

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.

OTHER TIPS

Consider using Fay.Text, if you enable OverloadedStrings and RebindableSyntax in the file fay will replace string literals with JS strings, these can have an Ord instance (but it seems like i forgot to add it! Patch it or use StandaloneDeriving until i get around to it). Like Data.Text these are more efficient, and they are also less problematic when using the FFI.

Also, we will probably have support for Eq and Ord instances soon, among other typeclasses.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top