emi*_*mic 0 haskell tuples list
我正在尝试编写一个函数来选择具有较低值的元组,而元组由一个单词和一个值组成.
例如,对于像这样的元组列表:[("CHURCH",262),("PENCIL",311),("FLOUR",175),("FOREST",405),("CLASS", 105)],函数将返回("CLASS",105)
有人可以帮我吗?:)
非常感谢!
您正在寻找的功能minimumBy
中Data.List
的模块.它的类型是
minimumBy :: (a -> a -> Ordering) -> [a] -> a
Run Code Online (Sandbox Code Playgroud)
在您的情况下,comparing
从Data.Ord
具有该类型的模块导入也是有用的
comparing :: Ord a => (b -> a) -> b -> b -> Ordering
Run Code Online (Sandbox Code Playgroud)
这可以让你给它一个"访问器"功能来创建一个订单.所以在这种情况下你可以做到
minimumSnd :: [(String, Int)] -> (String, Int)
minimumSnd = minimumBy (comparing ???)
Run Code Online (Sandbox Code Playgroud)
我会让你填写,???
在这一点上应该很容易.你的访问者函数comparing
会为你的类型传递什么?
如果您想为此编写自定义函数,我建议使用该fold
模式.我们也可以借此机会通过返回Maybe
类型来使其更安全,更通用的是不要求它是以下列表(String, Int)
:
minimumSnd :: (Ord b) => [(a, b)] -> Maybe (a, b)
minimumSnd = go Nothing
where
-- If the list is empty, just return our accumulator
go acc [] = acc
-- If we haven't found a minimum yet, grab the first element and use that
go Nothing (x:xs) = go (Just x) xs
-- If we have a minimum already, compare it to the next element
go (Just currentMin) (x:xs)
-- If it's <= our current min, use it
| snd x <= snd currentMin = go (Just x) xs
-- otherwise keep our current min and check the rest of the list
| otherwise = go (Just currentMin) xs
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
197 次 |
最近记录: |