昨天初次尝试用Haskell编了一个小的程序,用来检测一个列表有没有重复的元素。习惯了命令式编程语言后,尝试这种宣告式编程(Declarative programming) 稍微有点不习惯。
module Main where
multiply :: [a] -> [b] -> [(a, b)]
multiply [] [] = []
multiply _ [] = []
multiply [] _ = []
multiply [x] [y] = [(x, y)]
multiply [x] (y:ys) = (x, y) : (multiply [x] ys)
multiply (x:xs) [y] = (x, y) : (multiply xs [y])
multiply (x:xs) (y:ys) = (x, y) : ((multiply xs [y]) ++ (multiply [x] ys) ++ (multiply xs ys))
equalPair :: Eq a => (a, a) -> Bool
equalPair (a, b) = fst (a, b) == snd (a, b)
makePair :: [a] -> [(a, a)]
makePair [] = []
makePair [x] = []
makePair [x, y] = [(x, y)]
makePair (x:xs) = (multiply [x] xs) ++ (makePair xs)
main = all ( (==) False )
( map equalPair (makePair [1,2,3,4]) )
这个程序思路很直接,就是先两两配对,然后检查这些对中有无相等的。但这或许不是最快的一个实现。
没有评论:
发表评论