haskell中单词和值元组的较低值

emi*_*mic 0 haskell tuples list

我正在尝试编写一个函数来选择具有较低值的元组,而元组由一个单词和一个值组成.

例如,对于像这样的元组列表:[("CHURCH",262),("PENCIL",311),("FLOUR",175),("FOREST",405),("CLASS", 105)],函数将返回("CLASS",105)

有人可以帮我吗?:)

非常感谢!

bhe*_*ilr 7

您正在寻找的功能minimumByData.List的模块.它的类型是

minimumBy :: (a -> a -> Ordering) -> [a] -> a
Run Code Online (Sandbox Code Playgroud)

在您的情况下,comparingData.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)