Haskell - 将函数元组应用于值元组? [英] Haskell - apply tuple of functions to tuple of values?

查看:26
本文介绍了Haskell - 将函数元组应用于值元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示某个状态的值元组,并想通过加法(移位)来转换它.我的值是 (Int, [Int], Int) 的更长版本,我想要这样的概念(但不是字面意思):

I have a tuple of values representing some state, and want to translate it by an addition (shift). My values are a longer version of ( Int, [Int], Int), and I want something conceptually (but not literally) like this:

shift n = ??? (+n) (id, map, id)     -- simple(?)

相当于:

shift n (a, b, c) = (a+n, map (+n) b, c+n)

我很高兴使用这种明确的函数用法,但想知道是否有使用 Applicative 或 Arrows 或 ... 的更惯用的无点版本,或者他们是否会最终混淆事物.本以为免点版的操作的基本结构更清晰.

I am happy to just go with this explicit function usage, but wondered it there was a more idiomatic point-free version using Applicative or Arrows or ..., or if they would just end-up obfuscating things. I thought that the point-free version shows the basic structure of the operation more clearly.

推荐答案

使用 DeriveFunctor 语言扩展你可以编写

With the DeriveFunctor language extension you can write

data MyState a = MyState a [a] a
    deriving (Functor)

派生实例看起来像

instance Functor MyState where
    fmap f (MyState a bs c) = MyState (f a) (map f bs) (f c)

现在你可以定义

shift :: MyState Int -> MyState Int
shift n = fmap (+n)

(你说你的元组比 (Int, [Int], Int) 还要长,所以你可能想使用记录语法来定义你的状态类型.)

(You say your tuple is even longer than (Int, [Int], Int), so you may want to define your state type using record syntax.)

这篇关于Haskell - 将函数元组应用于值元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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