在Haskell中将多个函数应用于相同的无值点风格 [英] Applying multiple functions to the same value point-free style in Haskell

查看:85
本文介绍了在Haskell中将多个函数应用于相同的无值点风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一天我很无聊,想锻炼我的大脑,所以我决定做 99个Haskell问题,但只限于自己以无点的方式去做。当我以无点式的方式做事情时,似乎出现了很多问题:如何将多个函数应用于相同的值,同时将每个结果保留为独立的实体?使用尖括号:

  foobar x = [id x,reverse x] 

我以目前的免记分方式提出了一些建议:

  foobar'=`map` [id,reverse]($ x)

我似乎无法在那里得到 x 其他人已经发布了如何使用阅读器 monad,但这不是唯一的方法。事实证明,你的第二个功能非常接近。我认为你的意思是发布

  foobar'x =(`map` [id,reverse])($ x)

由于 x 已经接近最右边的位置,你快到了。首先,将($ x)部分转换为函数,因为使用起来更容易一些:

  - 通过右运算符部分的定义
foobar'2 x =(`map` [id,reverse])(\y - >($)yx)

接下来从lambda体中移除 x 通过将一个新变量带入作用域,并将函数应用于 x

   -  lambda抽象我认为... 
foobar'2 x =(`map` [id,reverse])$(\zy - >($)yz)x

将此应用程序重写为函数组合,然后您可以减少:

   - 根据'。'的定义
foobar'3 x =(`map` [id,reverse])。 (\ z y - >($)y z)$ x

- 减少
foobar'4 =(`map` [id,reverse])。 (\zy->($)yz)

最后,请注意我们可以替换lambda与一个函数

   - 根据`flip`的定义
foobar'5 =(`map` [id,反向])。翻转($)

并且您有一个免费的表单。


I was bored one day and wanted to exercise my brain, so I decided to do the 99 Haskell Problems but restricted myself to doing them in point-free style. A problem that seems to crop up a lot when I'm doing things in point-free style is this: How do you apply multiple functions to the same value while keeping each result as an independent entity? Using pointed notation:

foobar x = [id x, reverse x]

And what I've come up with so far in point-free notation:

foobar' = `map` [id, reverse] ($ x)

I can't seem to get that x off the end of there.

解决方案

Others have already posted how you can do this using the Reader monad, but that's not the only way. It turns out that your second function is pretty close. I think you meant to post

foobar' x = (`map` [id, reverse]) ($ x)

Since the x is already near a rightmost position, you're almost there. First, transform the section ($ x) into a function, because it's a bit easier to work with:

-- by the definition of a right operator section
foobar'2 x = (`map` [id, reverse]) (\y -> ($) y x)

Next remove the x from the lambda body by bringing a new variable into scope, and applying the function to x

-- lambda abstraction I think...
foobar'2 x = (`map` [id, reverse]) $ (\z y -> ($) y z) x

Rewrite this application as a function composition, and then you can eta reduce:

-- by definition of '.'
foobar'3 x = (`map` [id, reverse]) . (\z y -> ($) y z) $ x

-- eta reduction
foobar'4 = (`map` [id, reverse]) . (\z y -> ($) y z)

Finally, notice that we can replace the lambda with a function

-- by definition of `flip`
foobar'5 = (`map` [id,reverse]) . flip ($)

and you have a point-free form.

这篇关于在Haskell中将多个函数应用于相同的无值点风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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