gpt4 book ai didi

haskell - 有没有办法对列表中间的值进行模式匹配?还是在最后?

转载 作者:行者123 更新时间:2023-12-04 06:57:37 25 4
gpt4 key购买 nike

有点像

getFirstError :: [Either a b] -> a
getFirstError (x:y:...:Left w:z) = w

使用 Haskell,但了解其他具有模式匹配的语言如何实现这一点可能会很有趣。

最佳答案

尽管有其他答案,您可以使用 GHC 中的 View 模式扩展来执行此操作:

   getFirstError ((msum . map test) -> Just x) = x
where test (Left x) = Just x
test (Right x) = Nothing

或者使用模式守卫:

   getFirstError (xs) | Just x <- (msum $ map test xs) = x
where test (Left x) = Just x
test (Right) x = Nothing

关于haskell - 有没有办法对列表中间的值进行模式匹配?还是在最后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6634466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com