-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.hs
44 lines (34 loc) · 1.15 KB
/
sort.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import System.IO
import System.Environment
data Tree a = Nil | Node (Tree a) a (Tree a)
deriving (Show, Eq, Read)
singleton :: a -> Tree a
singleton x = Node Nil x Nil
insert :: (Ord a) => Tree a -> a -> Tree a
insert Nil x = singleton x
insert (Node left v right) x
| x == v = Node left v right
| x < v = Node (insert left x) v right
| x > v = Node left v (insert right x)
inorder :: (Ord a) => Tree a -> [a]
inorder Nil = []
inorder (Node left v right) = inorder left ++ [v] ++ inorder right
fromList :: (Ord a) => [a] -> Tree a
fromList = foldl insert Nil
sort :: (Ord a) => [a] -> [a]
sort xs = inorder (fromList xs)
main = do
args <- getArgs
contents <- readFile (head args)
let list = split (==',') (filter (/= '\n') contents)
let intlist = map readInt list
writeFile "output.txt" (stripChars "[]" (show (sort intlist)) ++ "\n")
readInt :: String -> Int
readInt = read
stripChars :: String -> String -> String
stripChars = filter . flip notElem
split :: (Char -> Bool) -> String -> [String]
split p s = case dropWhile p s of
"" -> []
s' -> w : split p s''
where (w, s'') = break p s'