简体   繁体   中英

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, eg maybe and either .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM