Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

haskellを触ってみる

参考にしたのはこちら
高階関数 - ウォークスルー Haskell


まず基本をならった。

-- haskell sample
-- putStrLn "Hello World!"
-- main = do { putStrLn "hello" ; putStrLn "world" }
{-
 ブロックコメント
-}

main = do { print (funcC 3)}

helloKat :: String
helloKat = "hello, Kat"

{-
   階乗計算関数
-}

fact:: Int -> Int
fact 0 = 1
fact x = x * fact (x - 1)

factExample :: [Int]
factExample = map fact [1,2,3]

{-
   絶対値関数
-}

-- if文は式なのでelse省略できない。
absolute :: Int -> Int
absolute x = if x < 0 then -x else x

{-
  円柱面積
-}
-- let式で局所的なsqare関数とbase変数を定義している。
cylinder :: Double -> Double -> Double
cylinder r h = let  square x = x * x
                    base = 3.14 * square r
                in h * base
{-
  Σf(i)の計算
-}
summation :: (Int -> Int) -> Int -> Int
summation f 1 = f 1
summation f n = f n + summation f (n-1)

{-
  λ抽象を用いた足し算
-}
add = \x y -> x + y

{-
  関数合成
-}

funcA :: Int -> Int
funcA x = x + 1

funcB :: Int -> Int
funcB x = x * 2

funcC :: Int -> Int
funcC = funcB.funcA


{-
  関数適用
-}
funcD :: Int -> Int
funcD x =  funcB $ funcA x