Haskell中的点运算符:需要更多解释 [英] Dot Operator in Haskell: need more explanation

查看:75
本文介绍了Haskell中的点运算符:需要更多解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  sumEuler = sum。我想知道点运算符在这个Haskell代码中做了什么:

(地图欧拉)。 mkList

整个源代码如下。



我的理解



点运算符使用两个函数 sum map euler 的结果以及 mkList 的结果作为输入。



但是, sum 不是函数,它是函数的参数,对吗?那么这里发生了什么?

另外,(map euler)在做什么?

代码



mkList :: Int - > [Int]
mkList n = [1..n-1]

euler :: Int - > Int
euler n = length(filter(relprime n)(mkList n))

sumEuler :: Int - > Int
sumEuler =总和。 (地图欧拉)。 mkList


解决方案

简单地说,

是函数组合,就像在数学中一样:

  f(gx)=(f。g) x 

在你的情况中,你正在创建一个新函数 sumEuler 也可以像这样定义:

pre $ sum $ u $ sum

示例中的样式称为无点样式 - 函数的参数省略。这在许多情况下使代码更清晰。 (第一次看到它可能很难,但是你会在一段时间后习惯它,这是一个常见的Haskell习惯用法。)



如果你仍然困惑,它可能有助于将与UNIX管道相关联。如果 f 的输出变成 g 的输入,其输出变为 h 的输入,你可以在命令行上写入,比如 f < x | g | ħ。在Haskell中,的作用类似于UNIX | ,但是向后 - h。 G 。 f $ x 。我发现这种表示法在处理列表时非常有用。不要像 map(\ x - > x * 2 + 10)[1..10] 这样笨拙的构造,您可以只写 (+10)。 (* 2)< $> [1..10] 。 (并且,如果您只想将该函数应用于单个值,它是(+ 10)。(* 2)$ 10 。一致!)



Haskell wiki有一篇很好的文章,内容更详细: http:/ /www.haskell.org/haskellwiki/Pointfree


I'm trying to understand what the dot operator is doing in this Haskell code:

sumEuler = sum . (map euler) . mkList

The entire source code is below.

My understanding

The dot operator is taking the two functions sum and the result of map euler and the result of mkList as the input.

But, sum isn't a function it is the argument of the function, right? So what is going on here?

Also, what is (map euler) doing?

Code

mkList :: Int -> [Int]
mkList n = [1..n-1]

euler :: Int -> Int
euler n = length (filter (relprime n) (mkList n))

sumEuler :: Int -> Int
sumEuler = sum . (map euler) . mkList

解决方案

Put simply, . is function composition, just like in math:

f (g x) = (f . g) x

In your case, you are creating a new function, sumEuler that could also be defined like this:

sumEuler x = sum (map euler (mkList x))

The style in your example is called "point-free" style -- the arguments to the function are omitted. This makes for clearer code in many cases. (It can be hard to grok the first time you see it, but you will get used to it after a while. It is a common Haskell idiom.)

If you are still confused, it may help to relate . to something like a UNIX pipe. If f's output becomes g's input, whose output becomes h's input, you'd write that on the command-line like f < x | g | h. In Haskell, . works like the UNIX |, but "backwards" -- h . g . f $ x. I find this notation to be quite helpful when, say, processing a list. Instead of some unwieldy construction like map (\x -> x * 2 + 10) [1..10], you could just write (+10) . (*2) <$> [1..10]. (And, if you want to only apply that function to a single value; it's (+10) . (*2) $ 10. Consistent!)

The Haskell wiki has a good article with some more detail: http://www.haskell.org/haskellwiki/Pointfree

这篇关于Haskell中的点运算符:需要更多解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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