Skip to content

Instantly share code, notes, and snippets.

Created January 16, 2017 12:33
Show Gist options
  • Save anonymous/fd16e158a0edb00e9d5dd0acfe1f0eb7 to your computer and use it in GitHub Desktop.
Save anonymous/fd16e158a0edb00e9d5dd0acfe1f0eb7 to your computer and use it in GitHub Desktop.
-- Deep Learning from Scratch
-- Chapter 01
module Ch01.Main where
import Prelude hiding (lookup)
import Control.Monad
main :: IO ()
main = do
-- 算術計算
let a1 = 1 - 2
let a2 = 4 * 5
let a3 = 7 / 5
let a4 = 3 ^ 2
putStrLn $ show a1
putStrLn $ show a2
putStrLn $ show a3
putStrLn $ show a4
-- データ型
-- Prelude> :t 10
-- 10 :: Num t => t
-- Prelude> :t 2.718
-- 2.718 :: Fractional t => t
-- Prelude> :t "hello"
-- "hello" :: [Char]
-- 変数
let x = 10
putStrLn $ show x
let x = 100 -- Fractal型
putStrLn $ show x
let y = 3.14
putStrLn $ show (x * y)
-- 配列(リスト)
let a = [1,2,3,4,5]
putStrLn $ show a
putStrLn $ show $ length a
putStrLn $ show $ a !! 0
putStrLn $ show $ a !! 4
let a' = insert 4 99 a
putStrLn $ show $ a'
putStrLn $ show $ take 2 a'
putStrLn $ show $ drop 1 a'
putStrLn $ show $ take 3 a'
putStrLn $ show $ take (length a' - 1) a'
-- ディクショナリ
let me = [("height", 180)]
let me' = ("weight", 70):me
putStrLn $ show $ me
putStrLn $ show $ me'
-- ブーリアン
let hungry = True
let sleepy = False
putStrLn $ show $ not hungry
putStrLn $ show $ hungry && sleepy
putStrLn $ show $ hungry || sleepy
-- if
when hungry $ putStrLn "I'm hungry"
let hungry = False
if hungry then putStrLn "I'm hungry"
else putStrLn "I'm not hungry" >>
putStrLn "I'm sleepy"
-- for
-- [IO ()]
for (\i -> putStrLn $ show i) [1,2,3]
-- 補助関数
-- 配列(リスト)
insert :: Int -> Int -> [Int] -> [Int]
insert i v lst =
let idx = (length lst) - i in
foldr (\x acc -> if length (x:acc) == idx then v:acc else x:acc) [] lst
-- ディクショナリ
lookup :: (Eq k) => k -> [(k,v)] -> Maybe v
lookup key [] = Nothing
lookup key ((k,v):rest)
| key == k = Just v
| otherwise = lookup key rest
-- Pythonのディクショナリ
-- >>> me = {'height':180}
-- >>> me['height']
-- 180
-- >>> me['weight'] = 70
-- >>> me
-- {'weight': 70, 'height': 180}
-- >> me['hoge']
-- Traceback (most recent call last):
-- File "<stdin>", line 1, in <module>
-- KeyError: 'hoge'
-- for
for f = map f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment