Browse Source

Conditional Evaluation with Guards

ch03
Craige McWhirter 4 years ago
parent
commit
1cd7ffcbe0
No known key found for this signature in database GPG Key ID: B41FA6FF04CE4B93
  1. 5
      ch02/myDrop.hs
  2. 5
      ch03/BadTree.hs
  3. 7
      ch03/Lending.hs

5
ch02/myDrop.hs

@ -6,3 +6,8 @@ myDrop :: Int -> [a] -> [a]
myDrop n xs = if n <= 0 || null xs
then xs
else myDrop (n - 1) (tail xs)
-- Reworking myDrop using guards
niceDrop n xs | n <= 0 = xs
niceDrop _ [] = []
niceDrop n (_:xs) = niceDrop (n - 1) xs

5
ch03/BadTree.hs

@ -3,3 +3,8 @@
-- Incorrectly trying to compare for equality
bad_nodesAreSame (Noda a _ _) (Node a _ _) = Just a
bad_nodesAreSame _ _ = Nothing
-- Using guards to correctly comapre for equality
nodesAreSame (Node a _ _) (Node b _ _)
| a == b = Just a
nodesAreSame _ _ = Nothing

7
ch03/Lending.hs

@ -14,3 +14,10 @@ lend2 amount balance = if amount < reserve * 0.5
where reserve = 100
newBalance = balance - amount
-- Reworking lend to use guards
lend3 amount balance
| amount <= 0 = Nothing
| amount > reserve * 0.5 = Nothing
| otherwise = Jusr newBalance
where reserve = 100
newBalance = balance - amount
Loading…
Cancel
Save