2013-03-21 70 views
1
flushPoints :: [Card] -> Integer 
flushPoints [email protected](c1:hd) = 
    if flushPointsCalc True (suitCount hd) > 
     flushPointsCalc False (suitCount cs) 
    then flushPointsCalc True (suitCount hd) 
    else flushPointsCalc False (suitCount cs) 

让我们说,如果我有一个功能,如上面的一个,我将如何去缩短它?缩短/制作功能更简洁

我正在考虑做一个where hdFlush = flushPointsCalc True (suitCount hd)但我不能从hd上面声明。

我觉得在Haskell中会有一种合适的方式来做它,考虑它有多懒,但我不确定在哪里寻找。

回答

8

这正是标准max函数所做的:它选择较大的值。所以,你可以重写你的代码为:

flushPoints [email protected](c1:hd) = max (flushPointsCalc True (suitCount hd)) 
          (flushPointsCalc False (suitCount cs)) 

如果你只是想知道如何为flshPointsCalc True (suitCound hd)提供本地名称,你可以确实使用where条款:

flushPoints :: [Card] -> Integer 
flushPoints [email protected](c1:hd) = 
    if hdFlush > csFlush then hdFlush else csFlush 
    where hdFlush = flushPointsCalc True (suitCount hd) 
     csFlush = flushPointsCalc False (suitCount cs) 

[email protected](c1:hd)模式位于flushPoints函数下的where块的范围内,因此您可以在其中访问hd

+0

啊,我正在使用最大的,由于某种原因它没有工作。但我可能在某个地方错过了一个支架。 – rlhh 2013-03-21 06:22:09

+1

@ user1043625:“最大”和“最大”是不同的功能。 “最大”给你一个列表中最大的元素,其中'max'给你两个参数中较大的一个。你可以通过查看他们的类型签名来看到差异。 – 2013-03-21 06:24:29

+0

好吧,我不知道有两个不同的功能(最大和最大),并感谢进一步的澄清。 :d – rlhh 2013-03-21 06:25:57