おかしなソート関数を実装してみよう

30分プログラム、その558。おかしなソート関数を実装してみよう。
訊くところによると、PHPの比較演算子は推移律が成り立ってないらしい。おそろしい話ですね。
これをあえて、Haskellでもやってみよう。きっと、Ordクラスを実装すればできるだろう。

使い方

*Main> sort $ map PHPString ["1e1", "1f1", "9"]
[9,1e1,1f1]
*Main>  sort $ map PHPString ["9", "1e1", "1f1"]
[1f1,9,1e1]

ソースコード

import Data.Char
import Data.List
newtype PHPString = PHPString String deriving Eq

isInt = all (\s -> isDigit s || s == 'e')

toFloat :: String -> Float
toFloat s = case takeWhile (\s -> isDigit s || s == 'e') s of
              [] -> 0
              xs -> read xs

instance Ord PHPString where
    compare (PHPString x) (PHPString y)
        | isInt x && isInt yt  = toFloat x `compare` toFloat y
        | otherwise = x `compare` y

instance Show PHPString where
    show (PHPString s) = s

s = sort $ map PHPString ["1e1", "1f1", "9"]
t = sort $ map PHPString ["9", "1e1", "1f1"]