Quick sort:
-- First variant:
qsort :: (Ord a) => [a] -> [a]
qsort [] = []
qsort (x:xs) = left x ++ [x] ++ right x
where left n = qsort [m | m <- xs, m <= n]
right n = qsort [m | m <- xs, m > n]
-- λ: qsort [10,2,5,3,1,6,7,4,2,3,4,8,9]
-- [1,2,2,3,3,4,4,5,6,7,8,9,10]
I see the left
and right
functions are almost identical. Therefore I want to rewrite it shorter... Something like that:
-- Second variant:
qsort' :: (Ord a) => [a] -> [a]
qsort' [] = []
qsort' (x:xs) = (srt <=) ++ [x] ++ (srt >)
where srt f = qsort' [m | m <- xs, m f x]
But I get errors when I try to load this into ghci
:
λ: :load temp
[1 of 1] Compiling Main ( temp.hs, interpreted )
temp.hs:34:18:
Couldn't match expected type `[a]'
with actual type `(t0 -> [a]) -> Bool'
Relevant bindings include
srt :: forall t. t -> [a] (bound at temp.hs:35:9)
xs :: [a] (bound at temp.hs:34:11)
x :: a (bound at temp.hs:34:9)
qsort' :: [a] -> [a] (bound at temp.hs:33:1)
In the first argument of `(++)', namely `(srt <=)'
In the expression: (srt <=) ++ [x] ++ (srt >)
In an equation for qsort':
qsort' (x : xs)
= (srt <=) ++ [x] ++ (srt >)
where
srt f = qsort' [m | m <- xs, m f x]
temp.hs:34:37:
Couldn't match expected type `[a]'
with actual type `(t1 -> [a]) -> Bool'
Relevant bindings include
srt :: forall t. t -> [a] (bound at temp.hs:35:9)
xs :: [a] (bound at temp.hs:34:11)
x :: a (bound at temp.hs:34:9)
qsort' :: [a] -> [a] (bound at temp.hs:33:1)
In the second argument of `(++)', namely `(srt >)'
In the second argument of `(++)', namely `[x] ++ (srt >)'
In the expression: (srt <=) ++ [x] ++ (srt >)
temp.hs:35:38:
Could not deduce (a ~ (t -> a -> Bool))
from the context (Ord a)
bound by the type signature for qsort' :: Ord a => [a] -> [a]
at temp.hs:32:11-31
`a' is a rigid type variable bound by
the type signature for qsort' :: Ord a => [a] -> [a]
at temp.hs:32:11
Relevant bindings include
m :: a (bound at temp.hs:35:29)
f :: t (bound at temp.hs:35:13)
srt :: t -> [a] (bound at temp.hs:35:9)
xs :: [a] (bound at temp.hs:34:11)
x :: a (bound at temp.hs:34:9)
qsort' :: [a] -> [a] (bound at temp.hs:33:1)
The function `m' is applied to two arguments,
but its type `a' has none
In the expression: m f x
In a stmt of a list comprehension: m f x
Failed, modules loaded: none.
λ:
I read the error message, but I don't understand the reason still...