【问题标题】:Choosing data from a list of tuples in Haskell从 Haskell 中的元组列表中选择数据
【发布时间】:2011-03-28 14:56:18
【问题描述】:

我在 Haskell 中有一个 :: [((a, b), (a, b), (a, b))] 类型的元组列表。

在某些情况下,3 个点 (a, b) 表示 U 形曲线上的(时间,值)对,第一个点在初始时间 t1 在曲线 x1 上具有最大值,第三个点具有更大的时间 t3=t1+dt 和一个值 x3

我想通过获取最大 t3 - t1 的元组,然后返回值 x2 - x1,找到列表 [((t1, x1), (t2, x2), (t3, x3))] 中最宽 U 的范围。

我能想到的唯一方法是首先将列表中的每个元组映射到t3 - t1,找到它的索引,然后计算原始列表中该索引的 x2 - x1。有没有更优雅的方法来做到这一点?

findMaxTime :: [((a, b), (a, b), (a, b))] -> Int
findMaxTime list = elemIndex (==min) $ map (\(x, y, z) -> fst z - fst x)
                       where min = minimum $ map (\(x, y, z) -> fst z - fst x)

findMaxVal :: [((a, b), (a, b), (a, b))] -> b
findMaxVal list = list !! findMaxTime list

任何帮助将不胜感激。

谢谢,阿什

【问题讨论】:

    标签: list haskell tuples


    【解决方案1】:

    您可以将maximumBycomparing 一起使用:

    module Main where
    
    import Data.Ord (comparing)
    import Data.List (maximumBy)
    
    findMaxVal :: (Num a, Ord a, Num b, Ord b) => [((a, b), (a, b), (a, b))] -> b
    findMaxVal = xWidth . maximumBy (comparing tWidth)
      where
        xWidth ((_, x1), (_, x2), _) = x2 - x1
        tWidth ((t1, _), _, (t3, _)) = t3 - t1
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多