Haskell:使用$的函数应用程序 [英] Haskell: Function application with $
问题描述
在下面的代码片段中,您可以看到我在Haskell中编写的两个collatz函数。对于递归应用程序,我在第一个示例(collatz)中使用括号来获得正确的优先级。
正如我刚刚使用$学习函数应用程序时,我试图重写函数(collatz')使用那个东西。但是,我遇到以下错误:
无法匹配预期类型`[a]'
与推断类型`a1 - > [a1]'在'(:)'的第二个参数中,即`collatz''在'($)'的第一个参数中,即`n:
collatz''在表达式中:n: collatz'$ n`div` 2
collatz ::(Integral a)=> a - > [a]
collatz 1 = [1]
collatz n |甚至n = n:collatz(n`div` 2)
|否则= n:collatz(n * 3 + 1)
collatz'::(积分a)=> a - > [a]
collatz'1 = [1]
collatz'n |甚至n = n:collatz'$ n`div` 2
|否则= n:collatz'$ n * 3 + 1
这让我感到奇怪,工作。所以我尝试了一个类似的例子:
True:[even $ 3`div` 3]
code>
我很感激,如果有人可以看看它并告诉我我做错了什么。
$
优先级较低,然后:
(还有其他任何东西),所以你的函数解析为
(n:collatz')$(n` div` 2)
这会导致您的类型错误。 的第二个参数:
需要一个列表,但您需要传递collatz函数。
如果您仍想避免3n + 1部分的括号,你可以做如下的事情:
(n :)。 collatz'$ n`div` 2
n:(collatz'$ n`div` 2)
<尽管这些并不一定比原来更清洁。如果你想知道,第一个例子中的(n:)
是 \ x - >的语法糖。 n:x
In the following snippet, you can see my two collatz functions I wrote in Haskell. For the recursive application I used parentheses in the first example (collatz) to get the right precedence.
As I have just learnt function application with $, I tried to rewrite the function (collatz') using that thing. However, I encounter the following error:
Couldn't match expected type `[a]' against inferred type `a1 -> [a1]' In the second argument of `(:)', namely `collatz'' In the first argument of `($)', namely `n : collatz'' In the expression: n : collatz' $ n `div` 2
collatz :: (Integral a) => a -> [a]
collatz 1 = [1]
collatz n | even n = n : collatz (n `div` 2)
| otherwise = n : collatz (n * 3 + 1)
collatz' :: (Integral a) => a -> [a]
collatz' 1 = [1]
collatz' n | even n = n : collatz' $ n `div` 2
| otherwise = n : collatz' $ n * 3 + 1
It seamed weird to me that this didn't work. So I tried a similar example that worked:
True : [even $ 3 `div` 3]
I'd appreciate it, if somebody could take a look at it and tell me what I'm doing wrong.
$
has lower precedence then :
(and also anything else) so your function is parsing as
(n : collatz') $ (n `div` 2)
This leads to your type error. The second argument of :
expects a list but you are passing the collatz function instead.
If you still want to avoid the parenthesis around the 3n+1 part you can do something like the following
(n:) . collatz' $ n `div` 2
n : (collatz' $ n `div` 2)
although these are not necessarily cleaner then the original. In case you are wondering, the (n:)
in the first example is a syntactic sugar for \x -> n : x
这篇关于Haskell:使用$的函数应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!