再帰で
uniq [] = [] uniq (x:xs) = x:uniq (filter (/=x) xs)
と書いてから,こんな関数ありそうだなぁと思ったらやっぱりあった。
高階関数版:
uniq2 :: (Eq a) => [a] -> [a] uniq2 = foldl (\a e -> if (elem e a) then a else a ++ [e]) []
型を明示しないとダメ。
Prelude> :l uniq2.hs [1 of 1] Compiling Main ( uniq2.hs, interpreted ) uniq2.hs:2:27: Ambiguous type variable `b' in the constraint: `Eq b' arising from use of `elem' at uniq2.hs:2:27-34 Possible cause: the monomorphism restriction applied to the following: uniq2 :: [b] -> [b] (bound at uniq2.hs:2:0) Probable fix: give these definition(s) an explicit type signature or use -fno-monomorphism-restriction Failed, modules loaded: none.
> 型を明示しないとダメ。
または引数を書くことですね。(単相性限定、単相性制限)
uniq2 xs = foldl (¥a e -> if (elem e a) then a else a ++ [e]) [] xs