Created
August 4, 2017 03:54
-
-
Save as-capabl/3919b5e466a7b454b139cf99d8c5d3df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE BangPatterns #-} | |
import Data.List (foldl') | |
-- お題:リスト中の偶数を全部足す | |
-- 最高 | |
sumEven1 :: [Int] -> Int | |
sumEven1 = foldl' (+) 0 . filter even | |
-- 書いてしまいがちなクソコード | |
sumEven2 :: [Int] -> Int | |
sumEven2 = foldl' (\sm x -> if even x then sm + x else sm) 0 | |
-- 上を分かり易くしたもの | |
sumEven3 :: [Int] -> Int | |
sumEven3 = foldl' addIfEven 0 | |
where | |
addIfEven sm x | |
| even x = sm + x | |
| otherwise = sm | |
-- 再帰 | |
sumEven4 :: [Int] -> Int | |
sumEven4 l = sumEven4' l 0 | |
where | |
sumEven4' [] !sm = sm | |
sumEven4' (x:xs) !sm | |
| even x = sumEven4' xs (sm + x) | |
| otherwise = sumEven4' xs sm | |
main = | |
do | |
print $ sumEven1 [1..10] | |
print $ sumEven2 [1..10] | |
print $ sumEven3 [1..10] | |
print $ sumEven4 [1..10] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment