code review

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
isPrime n
    | n == 0 = False
    | n == 1 = False
    | n < 0 = isPrime (-n)
    | n < 4 = True
    | n `mod` 2 == 0 = False
    | n `mod` 3 == 0 = False
    | any ( (==0) . mod n ) [5..h] = False
    | otherwise = True
    where
        h = ( ceiling . sqrt . fromIntegral ) n

-- equality tests on numeric literals are equivalent to simple pattern matches

isPrime 0 = False
isPrime 1 = False
isPrime n
    | n < 0 = isPrime (-n)
    | n < 4 = True
    | n `mod` 2 == 0 = False
    | n `mod` 3 == 0 = False
    | any ( (==0) . mod n ) [5..h] = False
    | otherwise = True
    where
        h = ( ceiling . sqrt . fromIntegral ) n

-- actually, let's just collapse those cases away anyway

isPrime n
    | n < 4 = n `elem` [2, 3]
    | n `mod` 2 == 0 = False
    | n `mod` 3 == 0 = False
    | any ( (==0) . mod n ) [5..h] = False
    | otherwise = True
    where
        h = ( ceiling . sqrt . fromIntegral ) n

-- any is short-circuiting

isPrime n
    | n < 4 = n `elem` [2, 3]
    | any ( (==0) . mod n ) ([2, 3] ++ [5..h]) = False
    | otherwise = True
    where
        h = ( ceiling . sqrt . fromIntegral ) n

-- if flag then False else True => not flag

isPrime n
    | n < 4 = n `elem` [2, 3]
    | otherwise = not $ any ( (==0) . mod n ) ([2, 3] ++ [5..h])
    where
        h = ( ceiling . sqrt . fromIntegral ) n

-- not . any p => all (not . p)

isPrime n
    | n < 4 = n `elem` [2, 3]
    | otherwise = all ( (/=0) . mod n ) ([2, 3] ++ [5..h])
    where
        h = ( ceiling . sqrt . fromIntegral ) n

-- prefer ($) to parentheses, seems to be an aesthetic that's hard to defend but very common

isPrime n
    | n < 4 = n `elem` [2, 3]
    | otherwise = all ( (/=0) . mod n ) ([2, 3] ++ [5..h])
    where
        h = ceiling . sqrt . fromIntegral $ n

-- the only behavioral change: decide that checking 4 is an okay speed hit to take given the improved code beauty

isPrime n
    | n < 4 = n `elem` [2, 3]
    | otherwise = all ( (/=0) . mod n ) [2..h]
    where
        h = ceiling . sqrt . fromIntegral $ n