Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
{-# 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
You can’t perform that action at this time.