Skip to content

Instantly share code, notes, and snippets.

@tan-yuki
Last active August 29, 2015 14:22
Show Gist options
  • Save tan-yuki/984647c51f8f9b7abd00 to your computer and use it in GitHub Desktop.
Save tan-yuki/984647c51f8f9b7abd00 to your computer and use it in GitHub Desktop.
すごいHaskell楽しく学ぼう 6章

6章モジュール

復習) 型と型クラス

Prelude> :t sum
sum :: Num a => [a] -> a
       ^^^
       型クラス

Prelude> :t length
length :: [a] -> Int
                 ^^^
                 型

6.1 モジュールをインポートする

  • nub: 重複した要素を削除
Prelude> :m + Data.List
Prelude Data.List> :t nub
nub :: Eq a => [a] -> [a]
Prelude Data.List> nub [1,2,3,4,5,1,6]
[1,2,3,4,5,6]
Prelude Data.List> nub [1,2,3,4,3,3,5,1,6]
[1,2,3,4,5,6]

実装してみた

import Data.List

nub0 :: (Eq a) => [a] -> [a]
nub0 [] = []
nub0 (x:xs)
  | x `elem` xs = nub0 xs
  | otherwise   = x : nub0 xs

nub1 :: (Eq a) => [a] -> [a]
nub1 = foldr (\x acc -> if x `elem` acc
             then acc else x:acc) []

nub2 :: (Eq a) => [a] -> [a]
nub2 = foldl (\acc x -> if x `elem` acc
             then acc else acc ++ [x]) []

nub3 :: (Eq a) => [a] -> [a]
nub3 = foldl go [] where
    go acc x
        | x `elem` acc = acc
        | otherwise    = acc ++ [x]

main = do
   putStrLn $ show $ nub  [1,2,3,4,3,3,2,5,1,6]  -- [1,2,3,4,5,6]
   putStrLn $ show $ nub0 [1,2,3,4,3,3,2,5,1,6]  -- [4,3,2,5,1,6]
   putStrLn $ show $ nub1 [1,2,3,4,3,3,2,5,1,6]  -- [4,3,2,5,1,6]
   putStrLn $ show $ nub2 [1,2,3,4,3,3,2,5,1,6]  -- [1,2,3,4,5,6]
   putStrLn $ show $ nub3 [1,2,3,4,3,3,2,5,1,6]  -- [1,2,3,4,5,6]

(もっとうまいやり方ありそう)

追記

http://stackoverflow.com/questions/16108714/haskell-removing-duplicates-from-a-list

大体同じ感じかな・・・?

6.2 標準モジュールの関数で問題を解く

単語を数える

  • 宿題
    • Data.Listを用いずにwordNumsを実装してみましょう。

シーザー暗号サラダ

  • negate
Prelude Data.List> :t negate
negate :: Num a => a -> a
Prelude Data.List> negate 5
-5
Prelude Data.List> negate -10

<interactive>:9:1:
    No instance for (Show (a0 -> a0)) arising from a use of ‘print’
    In a stmt of an interactive GHCi command: print it
Prelude Data.List> negate (-10)
10
Prelude Data.List> negate 0
0

6.3 キーから値のマッピング

Data.Mapに潜入せよ

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