LoginSignup
1
1

More than 5 years have passed since last update.

Haskellメモ

Last updated at Posted at 2015-01-24

個人的なメモ帳です。嘘書いてたらごめんなさい。

List

  • 結合
Prelude> [1,2,3] ++ [4]
[1,2,3,4]

下記はコンパイルエラー

Prelude> [1,2,3] ++ 4
  • 頭に結合
Prelude> 0 : [1,2,3]
[0,1,2,3]
fibonacci
fibonacci :: [Int]
fibonacci = 1 : 2 : zipWith (+) fibonacci (tail fibonacci)

これがfibonacci数列になるらしい。謎い。
私の中では多分こんな流れなんだろうということで自己解決。

   [1,2,...      <- fibonacci
+) [2,...        <- (tail fibonacci)
--------------
   [3,...        <- zipWith (+) fibonacci (tail fibonacci)

=>
   [1,2,3,..
+) [2,3,..
--------------
   [3,5,..

=>
   [1,2,3,5,..
+) [2,3,5,..
--------------
   [3,5,8,..

こんなの思いつく気がしない

追記)
上記のfibonacci数列の生成はとても遅いみたいです。
http://d.hatena.ne.jp/nishiohirokazu/20100622/1277208908

内包記法いろいろ実験

  • 1~10までの奇数のList
Prelude> [x | x <- [1..10], mod x 2 == 1]
[1,3,5,7,9]

↓でもOK(こっちのほうが見やすいかも)

Prelude> [x | x <- [1..10], x `mod` 2 == 1]
[1,3,5,7,9]
  • 2乗の和が100~400までの隣り合った数のList
Prelude> [(x, x + 1) | x <- [1..400],
  let sum = x^2 + (x + 1)^2, 100 <= sum && sum <= 400 ]
[(7,8),(8,9),(9,10),(10,11),(11,12),(12,13),(13,14)]

関数いろいろ実験

関数は上から評価される

  • func-test.hs
isSeven :: Int -> String
isSeven 7 = "This is seven"
isSeven x = "This is not seven"
Prelude> :l ./func-test.hs
[1 of 1] Compiling Main             ( func-test.hs, interpreted )
Ok, modules loaded: Main.
*Main> isSeven 7
"This is seven"
*Main> isSeven 8
"This is not seven"
  • reverse
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
*Main> reverse' "abcdefg"
"gfedcba"
*Main> reverse' [1,2,3]
[3,2,1]

ラムダ式でguard

map (\x -> case () of
  _ | x == 2 -> "two"
    | x == 4 -> "four"
  otherwise  -> show x) [1,2,3,4]
["1","two","3","four"]

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1