Haskell是否提供针对许多可能的数据构造函数进行模式匹配的习惯用法? [英] Does Haskell provide an idiom for pattern matching against many possible data constructors?

查看:69
本文介绍了Haskell是否提供针对许多可能的数据构造函数进行模式匹配的习惯用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理Haskell项目时,我正在处理

Working on a Haskell project, I'm dealing with the Event data type from the FSNotify package. The constructors for Event are all:

Added FilePath UTCTime
Modified FilePath UTCTime
Removed FilePath UTCTime

在我的代码中,我只想从Event中提取FilePath并执行相同的操作,而与类型构造函数无关.因此,我很想做一个lambda.

In my code, I'm only interested in extracting the FilePath from the Event and doing the same action regardless of the type constructor; because of this, I'm tempted to make a lambda.

不幸的是,当我将case表达式放入lambda中以对所有三种情况进行模式匹配时,代码的可读性下降.考虑到类型构造函数的相对同质性,是否有一些内置的成语来仅提取一个表达式中的FilePath而不需要手动进行模式匹配?

Unfortunately, the code suffers reduced readability when I drop a case expression into the lambda to pattern match against all three cases; is there some built-in idiom to extract just the FilePath in one expression without having to manually pattern match, given the relative homogeneity of the type constructors?

我尝试在调用watchDir动作时将此表达式作为匿名函数传递:

I've tried passing this expression as an anonymous function in a call to the watchDir action:

 wm <- startManager
 sw <- watchDir wm "." (\_ -> True) (\(_ f t) -> putStrLn f)

但是,可以预见的是,lambda的模式匹配中的无关紧要"值会导致解析错误.

But, predictably, the don't-care value in the lambda's pattern match causes a parse error.

推荐答案

最简单的方法是在类型声明中实际反映替代方案的同质性,而不是仅仅观察它:

The simplest way would be to actually reflect the homogenity of the alternatives in the type declaration, instead of just observing it:

data Action = Added | Modified | Removed

data Event = FileEvent Action FilePath UTCTime | OtherEvent ...

f :: Event -> FilePath
f (FileEvent _ path _) = path

通常,Haskell无法知道所有构造方法的替代方法都具有相同数量的参数和相同的类型,所以不,您不能抽象出替代方法的选择.

In general, Haskell has no way to know that all your constructor alternatives have the same number of arguments and the same type, so no, you can't abstract over the choice of alternative.

这篇关于Haskell是否提供针对许多可能的数据构造函数进行模式匹配的习惯用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆