list - 从 Haskell 中的元组列表中选择数据

标签 list haskell tuples

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

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

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

我能想到的唯一方法是首先将列表中的每个元组映射到 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

任何帮助,将不胜感激。

谢谢,阿什

最佳答案

您可以使用 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

关于list - 从 Haskell 中的元组列表中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462700/

相关文章:

python - 需要在 Python 中对长的、格式奇怪的数据集取平均值

python - 如何在Python中根据多个其他列表过滤列表?

Python 列表理解 : Using "if" Statement on Result of the Comprehension

haskell - 约束的笛卡尔积

list - 为什么haskell没有异构列表

python - 使用 Beautiful Soup 将多个列表项包装在新标签 ('ul'/'ol' )中?

haskell - Haskell顺序求值策略的 'r'前缀代表什么?

python - 如何从二维元组中选择一行

python - 从 Django 中的模型类生成可迭代选择元组

python-2.7 - 两个整数元组之间的范围?