简体   繁体   English

如何使用函子或应用程序在元组列表上重写此Haskell函数

[英]How can I use functors or applicatives to rewrite this Haskell function over lists of tuples

Is there a nicer way to write the following function fs' with functors or applicatives? 有没有更好的方法可以用函子或应用程序编写以下函数fs'

fncnB = (* 2)
fncnA = (* 3)
fs' fs = zip (map (fncnA . fst) fs) $ map (fncnB . snd) fs

I see from this question that I could rely on the functor instance of lists to map a single function acting over both elements of each tuple, or eg on the applicative instance of tuples to apply functions to just the second-half of a two-tuple, but I'm curious how functors and applicatives fit into the picture of operating over lists of multi-component data types. 我从这个问题中看到,我可以依靠列表的函子实例来映射作用在每个元组的两个元素上的单个函数,或者例如在元组的应用实例上将函数仅应用于两个元组的后半部分,但我很好奇函子和应用程序如何适合对多组分数据类型列表进行操作的图片。

A tuple is a bifunctor, so bimap is available. 元组是bifunctor,因此可以使用bimap

import Data.Bifunctor

fncnB = (* 2)
fncnA = (* 3)
fs' = map (bimap fncnA fncnB)

No third-party libraries required. 无需第三方库。

what you need is the mapPair function, it's defined in the utility-ht package but it's just 您需要的是mapPair函数,它是在Utility-ht包中定义的,但它只是

mapPair :: (a -> c, b -> d) -> (a,b) -> (c,d)
mapPair (f,g) (a,b) = (f a, g b) 

use 采用

Prelude> mapPair ((* 2), (* 3)) (2,3)
(4,9)

or 要么

Prelude> map (mapPair ((* 2), (* 3))) [(1,2),(2,3)]
[(2,6),(4,9)]

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

相关问题 如何在Applicatives上测试多态函数? - How can I test functions polymorphic over Applicatives? 是否有一系列 Haskell 函数用于对应用元组进行排序? - Is there a family of Haskell functions for sequencing tuples of applicatives? Haskell:如何创建一个不允许使用、一个或两个 Applicative 的函数? - Haskell: How do I create a function that allows none, one or two Applicatives? Haskell类型的Oz过滤nicta过程函子和应用程序的神奇世界 - Haskell type magical world of Oz filtering nicta course functors and applicatives 如何使用map函数在haskell中将元组列表分为两个列表? - How do I split a list of tuples into two lists in haskell using the map function? 没有应用程序的函数的示例 - Examples of Functors without Applicatives 如何将 3 元组列表转换为 Haskell 中的一个 3 元组列表? - How can I convert a list of 3-tuples into one 3-triple of lists in Haskell? 类型的函数和应用程序(* - > *) - > * - Functors and Applicatives for types of kind (* -> *) -> * haskell fmap。 fmap函数,函数超过两个仿函数 - haskell fmap . fmap function, function over two functors 如何在Haskell中将模式匹配与元组列表一起使用? - How do you use pattern matching with lists of tuples in Haskell?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM