2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Haskell プレリュード関数特集(1)

Last updated at Posted at 2020-11-09

はじめに

Haskellには、予め多くの組み込む関数が用意されています。
その関数は、予め読み込まれるモジュールの中で定義されています。
これをプレリュードと呼びます。
今回は、このプレリュード関数にどのようなものがあるのか、実際に試しながらその結果を踏まえまとめていこうと思います。
ちなみに今回参考にしている資料はこちらHaskell公式-Preludeです。

プレリュード関数

Bool型の関数

&&

例.hs
  True && False
=> False

   False && False
=> False

||

例.hs
   True || False
=> True

   False || False
=> False
not
例.hs
   not True
=> False

   not False
=> True

otherwise

trueと同値です。
ガードを読みやすくするために使用する。

例.hs
   otherwise
=> True

Maybe型の関数

either

下記の例で説明すると、Leftなら、(+1)をRightなら(+2)を処理する関数を渡してEitherを取り除きます。

例.hs
   either (+ 1) (* 2) $ Left 5
=> 6

Tuples型の関数

fst

ペアの最初の値を抽出します。

例.hs
   fst ("Hello", "World")
=> "Hello"

snd

ペアの2番目の値を抽出します。

例.hs
   snd ("Hello", "World")
=> "World"

curry

カリー化されていない関数をカリー化された関数に変換します。

例.hs
  (curry fst)  "Hello" "World"
=> "Hello"

uncurry

カリー化された関数をペアの関数に変換します。

例.hs
   (uncurry (-)) (3, 1)
=> 2

Eq型クラスの関数

(==)

例.hs
   1 == 1
=> True

   1 == 2
=> False

(/=)

例.hs
   1 /= 1
=> False

   1 /= 2
=> True

Ord型クラスの関数

(<)

例.hs
   1 < 1
=> False

   1 < 2
=> True

(<=)

例.hs
    1 <= 1
=> True

    1 <= 2
=> True

(>)

例.hs
    1 > 1
=> False

   1 > 2
=> False

   2 > 1
=> True

(>=)

例.hs
   1 >= 1
=> True

   1 >= 2
=> False

max

2つの値の大きい値を返す。

例.hs
   max 1 5
=> 5

min

2つの値の小さい値を返す。

例.hs
   min 1 5
=> 1

Enum型クラスの関数

succ

引数で受け取った値の次の値を返す。

例.hs
  succ 1
=> 2

pred

引数で受け取った値の前の値を返す。

例.hs
   pred 2
=> 1

toEnum

数値 → 列挙型へconvertします。

例.hs
data Pets =  Dog | Cat deriving (Show, Enum)

main :: IO ()
main =  do
        print (toEnum 0 :: Pets)

=> Dog

fromEnum

列挙型 → 数値へconvertします。

例.hs
data Pets =  Dog | Cat deriving (Show, Enum)

main :: IO ()
main =  do
        print $ fromEnum Dog

=> 0

おわり

今日はここまで、次回はBounded型クラスからはじめます。

2
0
3

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?