简体   繁体   English

Haskell中可能的无点模式匹配?

[英]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 . 是否可以在不必命名ab情况下编写add'em 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 我们可以定义一个操作来将两个参数的函数提升到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. 但是,如果你试图解决在整个地方展开和包装的实际问题(特别是对于newtypes),我经常定义一个mapf f (Type val) = Type (f val)函数,类似于fmap,然后不要导出它。 You can do the same for a n-ary data type just by passing more functions. 只需传递更多函数,就可以对n-ary数据类型执行相同的操作。 If the implementation isn't supposed to be secret, you can export it too (as fmap for unary). 如果实现不应该是秘密的,您也可以将其导出(作为一元的fmap)。 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 . 基本类型已经定义了这样的功能,例如maybeeither

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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