开发者

Point-free pattern matching possible in Haskell?

Given:

data TwoInts = TwoInts Int Int 

add'em :: TwoInts -> Int
add'em (TwoInts a b) = a+b

is it possible to write add'em without having to name a and b. Something like:

 add'em TwoInts = 开发者_开发百科(+) -- (Note: Fails to type check)


Via analogy to tuples,

data TwoInts = TwoInts { fst', snd' :: Int }

we can define an operation for lifting functions of two arguments onto a TwoInt

uncurry' f p =  f (fst' p) (snd' p)

Giving us the nice notation:

add'em = uncurry' (+)


In general I'd say no, it's not possible. However, if you are trying to solve the practical problem of unwrapping and wrapping all over the place (especially common with newtypes), I often define a mapf f (Type val) = Type (f val) function, analogous to fmap, and then don't export it. You can do the same for a n-ary data type just by passing more functions. If the implementation isn't supposed to be secret, you can export it too (as fmap for unary). I recommend either this kind of map function or views for complicated types because pattern matching will tie you to the implementation.

The basic types already have such functions defined, e.g. maybe and either.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜