2011-07-09 20 views

回答

6

可以,尽管其他的答案,在GHC做到这一点使用视图模式扩展:

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 
+0

你是否意外地忽略了模式卫士版本中的'Just'构造函数的匹配? – Rotsor

+0

另外,你需要用于错误类型的'Monoid'实例,这看起来不太合理,而'test'函数没有编译,因为它没有足够的括号。并且返回所有错误的连接而不是第一个错误。 – Rotsor

+0

替换'mconcat。地图测试 - >用'mconcat只是x'。 map(First。test) - > First(Just x)'应该这样做。 – Rotsor

1

不,没有。但是,您可以easiliy写函数使用递归:

getFirstError [] = error "getFirstError: empty list or no error" 
getFirstError (Left x : xs) = x 
getFirstError (_ : xs) = getFirstError xs 
2

没有,但你可以使用列表理解

getFirstError xs = head [ x | Left x <- xs ] 

需要注意的是,如果没有错误head将失败。

+3

和'head'失败本身就是一个错误不同的品种,所以你可以说这个函数总是会找到* some *错误,这种或那种方式! –

相关问题