Skip to content

Instantly share code, notes, and snippets.

@pphetra
Created May 24, 2015 09:43
Show Gist options
  • Select an option

  • Save pphetra/e29f64eba0a0fbb63edb to your computer and use it in GitHub Desktop.

Select an option

Save pphetra/e29f64eba0a0fbb63edb to your computer and use it in GitHub Desktop.
import Data.List
import Data.Maybe
import Data.HashMap.Strict
-- version แรก ต้องระวังเรื่อง lookup เจอตัวเอง code ก็เลยมี if เข้ามา ทำให้ code อ่านยาก่
solvev1 n s = case lookup' of
Just a -> let b = n - a in if a /= b then Just (a, b) else Nothing
_ -> Nothing
where table = Data.HashMap.Strict.fromList [(x,x) | x <- s]
lookup' = find (\x -> isJust $ Data.HashMap.Strict.lookup (n - x) table) s
-- หลังจากพิจารณาแล้ว เห็นว่า maybe ทั้งหลายสามารถห่ออยู่ใน do notaion ได้ ก็เลยจัดการเขียนใหม่
solvev2 n s = do
a <- find (\x -> isJust $ Data.HashMap.Strict.lookup (n - x) table) s
b <- Just (n - a)
if a /= b then Just (a, b) else Nothing
where table = Data.HashMap.Strict.fromList [(x,x) | x <- s]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment