Ash*_*Ash 5 haskell tuples list
我:: [((a, b), (a, b), (a, b))]在Haskell中有一个类型元组的元组列表.
对于某些上下文,3个点(a, b)表示具有第一个点的U形曲线上的(时间,值)对,在初始时间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
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激.
谢谢,阿什
你可以用maximumBy与comparing:
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
Run Code Online (Sandbox Code Playgroud)