5
2

More than 5 years have passed since last update.

Last updated at Posted at 2018-08-19

## 実装

すごH本を写経します。

#### ・maximum関数

リストの中で一番大きな数を返す関数。

``````maximum' :: (Ord a) => [a] -> a
maximum' [] = error "empty"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)
``````

#### ・再帰でよく使う共通のパターン x:xs

「基底部は空リストし、x:xsパターンで、リストの先頭要素をxに束縛し、残りをxsに束縛する」

#### ・replicate関数

``````replicate' :: Int -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x : replicate' (n-1) x
``````

#### ・reverse関数

リストを逆順にする

``````reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
``````

#### ・elem関数

``````elem' :: (Eq a) => a -> [a] -> Bool
elem' a [] = False
elem' a (x:xs)
| a == x = True
| otherwise = a `elem` xs
``````

## クイックソートを再帰で！

xより小さいか等しい要素を左に置きたい。そのためにリスト内包表記を使う。大きいものも同様。

``````quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerOrEqual = [a | a <- xs, a <= x]
larger = [a | a <- xs, a > x]
in quicksort smallerOrEqual ++ [x] ++ quicksort larger
``````

``````quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerOrEqual = filter (<= x) xs
larger = filter (> x) xs
in quicksort smallerOrEqual ++ [x] ++ quicksort larger
``````
5
2
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
5
2