简体   繁体   中英

Shortening/Making a function more concise

flushPoints :: [Card] -> Integer
flushPoints cs@(c1:hd)  = 
    if flushPointsCalc True (suitCount hd) > 
        flushPointsCalc False (suitCount cs)
    then flushPointsCalc True (suitCount hd)
    else flushPointsCalc False (suitCount cs)

Let's say if I have a function such as the one above, how would I go around shortening it?

I was thinking of doing a where hdFlush = flushPointsCalc True (suitCount hd) but that I can't since hd is declared up above.

I feel that there would be a proper way to do it in Haskell, considering how lazy it is but I'm not sure where to look.

This is exactly what the standard max function does: it choose the bigger value. So you can rewrite your code as:

flushPoints cs@(c1:hd) = max (flushPointsCalc True  (suitCount hd)) 
                             (flushPointsCalc False (suitCount cs))

If you just wanted to know how to give a local name for flshPointsCalc True (suitCound hd) , you can indeed use a where clause:

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

The cs@(c1:hd) pattern is in scope for the where block immediately under the flushPoints function, so you can access hd in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM