Skip to content

Instantly share code, notes, and snippets.

@TAKAyukiatkwsk
Last active December 27, 2015 22:29
Show Gist options
  • Save TAKAyukiatkwsk/7398954 to your computer and use it in GitHub Desktop.
Save TAKAyukiatkwsk/7398954 to your computer and use it in GitHub Desktop.
すごいHaskell本のメモ
-- リスト内包表記
[x*2 | x <- [1..10]]
-- [2,4,6,8,10,12,14,16,18,20]
-- 条件(述語)を追加できる。2倍した値が12以上のリスト
[x*2 | x <- [1..10], x*2 >= 12]
-- [12,14,16,18,20]
-- 複数のリストから値を取り出す。それぞれのリストの要素の組み合わせが結果のリストになる
[x+y | x <- [1,2,3], y <- [10,100,1000]]
-- [11,101,1001,12,102,1002,13,103,1003]
-- 文字列もリスト
-- 文字列から小文字を取り除く関数
let removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]
removeNonUppercase "HelloWORLD"
-- "HWORLD"
-- タプル: 複数の違う型の要素を格納して1つの値にするのに使う
-- 直角三角形を見つける問題
-- 3辺の長さは全て整数、各辺の長さは10以下、周囲の長さは24に等しい
-- まずは各要素が10以下であるトリプルを作る
let triples = [(a,b,c) | c <- [1..10], a <- [1..10], b <- [1..10] ]
-- ピタゴラスの定理がなりたち、斜辺(c)より短く(a)、もう一方(b)は(a)を超えないように
let rightTriangles = [ (a,b,c) | c <- [1..10], a <- [1..c], b <- [1..a], a^2 + b^2 == c^2 ]
rightTriangles
-- [(4,3,5),(8,6,10)]
-- 最後に周囲の長さが24のものを取り出す
let rightTriangles' = [ (a,b,c) | c <- [1..10], a <- [1..c], b <- [1..a], a^2 + b^2 == c^2, a+b+c == 24 ]
rightTriangles'
-- [(8,6,10)]
# 参考にRuby で書くと...
(1..10).map {|x| x * 2 }
#=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# ちょっとまどろっこしい...
a = []; (1..10).each { |x| a << x * 2 if x * 2>=12 }; a
#=> [12, 14, 16, 18, 20]
# リストから新しくリストを作る場合はHaskellの方がキレイに書ける感じがする
import System.IO
main = do
handle <- openFile "baabaa.txt" ReadMode
contents <- hGetContents handle
putStr contents
hClose handle
-- withFile を使う
import.System.IO
main = do
withFile "baabaa.txt" ReadMode $ \handle -> do
contents <- hGetContents handle
putStr contents
-- readFile
import System.IO
main = do
contents <- readFile "baabaa.txt"
putStr contents
# 上のコードをRubyで書くとこんな感じ?
file = File.open("baabaa.txt", "r")
contents = file.read
puts contents
file.close
# ブロックを使うイメージかな?
File.open("baabaa.txt", "r") do |file|
contents = file.read
puts contents
end
# File.read
contents = File.read("baabaa.txt")
puts contetns
@TAKAyukiatkwsk
Copy link
Author

ghci では :l hoge.hs でスクリプトファイルを読み込める。

@TAKAyukiatkwsk
Copy link
Author

このように書いても同じ結果となる

map (*2) [1..10]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment