haskell为现有函数添加任何内容

时间:2013-11-29 12:37:01

标签: function haskell add

嘿那里使用这个脚本:

smallestDifference3 :: Int -> Int -> Int -> Int
smallestDifference3 a b c
    | ((differenceAB < differenceBC) && (differenceBC < differenceAC)) = differenceAB
    | ((differenceAB < differenceAC) && (differenceAC < differenceBC)) = differenceAB
    | ((differenceBC < differenceAB) && (differenceAB < differenceAC)) = differenceBC
    | ((differenceBC < differenceAC) && (differenceAC < differenceAB)) = differenceBC
    | ((differenceAC < differenceBC) && (differenceBC < differenceAB)) = differenceAC
    | ((differenceAC < differenceAB) && (differenceBC < differenceBC)) = differenceAC
  where differenceAB 
         | a < b = -(a - b)
         | otherwise    = a - b
        differenceBC
         | b < c = -(b - c)
         | otherwise    = b - c
        differenceAC
         | a < c = -(a - c)
         | otherwise    = a - c

我可以键入三个整数并获得其中两个Integer的最小结果。 但是,如果我再添加一个INT,我该怎么办,所以我有:

smallestDifference4 :: Int -> Int -> Int -> Int -> Int
smallestDifference4 a b c d

// etc..

我应该使用“smallestDifference3”函数来获取这个或我需要做什么?问候!

1 个答案:

答案 0 :(得分:3)

引入一个带有列表的通用函数,即

smallestDifference :: [Int] -> Int

然后使用其他功能,例如

smallestDifference4 :: Int -> Int -> Int -> Int -> Int
smallestDifference4 a b c d = smallestDifference [a,b,c,d]

...当然,在那一点上,你可能只想放弃那些微小的功能,因为它们不会“拉自己的重量”。

话虽如此,您可以在现有功能方面更多地实现此功能。我们的想法是你需要一种方法来获得给定列表的所有可能的对,然后计算对成员的差异,然后选择最小值。

您需要一个“所有对”功能,如

pairs :: [a] -> [(a, a)]
pairs = concat . go
  where go [] = []
        go [x] = []
        go (x:xs) = map (\a -> (x,a)) xs : go xs

然后你可以像

那样做
smallestDifference = minimum
                   . map abs
                   . map (uncurry (-))
                   . pairs