Haskell Wisdom

Posted on October 9, 2006

Elendal: Hi, i am doing an assignment in haskell and I want to know if I can avoid calling same code twise can anybody help?

getOfSame [] _ = []
getOfSame hand x = if (length (filter (\x -> getRank x == (getRank(getHighCard hand))) hand) == x)
                    then filter (\x -> getRank x == (getRank(getHighCard hand))) hand
                    else getOfSame (removeHightCard hand) x

emk: Elendal: Let me take a look.
Pseudonym: Elendal, time to learn about where clauses.
Pseudonym: Oh, and guards.
emk: Elendal: A where clause, a let declaration, or a helper function.

Pseudonym:

foo x y = if c then e else t

Pseudonym: Can be refactored as:

foo x y
 | c   -> e
 | otherwise -> t

Pseudonym: The other thing is you can give expressions a name:
Pseudonym: foo x y = … someExpression … someExpression
Pseudonym: transform to:
Pseudonym: foo x y = … e … e
Pseudonym: where e = someExpression

dons: something like:

getOfSame hand x
      | length r == x = r
      | otherwise = getOfSame (removeHightCard hand) x
      where f c = getRank c == getRank (getHighCard hand)
            r   = filter f hand

dons: Elendal: the key is to use ‘where’ to record the result of the filter once, and then just reuse that result
Elendal: Thanks!
emk: Elendal: Good luck!
Pseudonym: BTW, bonus marks for the nice accumulator recursion.

Filed Under Uncategorized |

Leave a Comment

If you would like to make a comment, please fill out the form below.

Name

Email

Website

Comments

For spam detection purposes, please copy the number 8179 to the field below:

© Copyright 0xDEADBEEFCAFE • Powered by Wordpress • Design by Sebastin.

free web hit counter