はじめてのHaskell(6)

grepコマンド

関数

関数 概要
head リストの最初の要素を返す:[a]->a
tail 最初の要素をのぞいたリストを返す:[a]->[a]
filter リストの要素のうち、f x がTrueである要素を集めたリストを返す:
filter::(a -> Bool) -> [a] -> [a]
any リストの各要素に関数を適用し、いずれかの値がTrueならTrueを返す:
any::(a -> Bool ) -> [a] -> Bool
List.tails リストそのもの、リストの第二要素以降、リストの第三要素以降。。。。をリストに返す。
tails :: [a] -> a
List.isPrefixOf関数 リストがリストの先頭に一致するときTrueを返す。
isPrefixOf :: (Eq a ) => [a] -> [a] -> Bool

filter例
filter odd [1, 2, 3, 4, 5] -> [1, 3, 5]
(odd nはnが奇数のときTrue)

関数の使い方

Ex)
isPrefixOf pattern line

  • > pattern 'isPrefixOf' line

と英語の文法と同様な記載をすることができる。

where節

ある式だけ有効な定義を導入する

where 定義1
        定義2

定義1,定義2は式内のみで有効な定義

コマンド

以下のエラーが発生した為、package定義を修正して実行した。

エラー
$ ghc fgrep.hs 

fgrep.hs:1:8:
    Could not find module ‘System’
    It is a member of the hidden package ‘haskell98-2.0.0.3’.
    Use -v to see a list of the files searched for.

fgrep.hs:2:8:
    Could not find module ‘List’
    It is a member of the hidden package ‘haskell98-2.0.0.3’.
    Use -v to see a list of the files searched for.
修正
$ ghc -package haskell98 -hide-package base fgrep.hs -o grep
[1 of 1] Compiling Main             ( fgrep.hs, fgrep.o )
Linking grep ...

コード

import System
import List

main = do args <- getArgs
	  cs <- getContents
	  putStr $ fgrep (head args) cs

fgrep :: String -> String -> String
fgrep pattern cs = unlines $ filter match $ lines cs
  where
    match :: String -> Bool
    match line = any prefixp $ tails line

    prefixp :: String -> Bool
    prefixp line = isPrefixOf pattern line

パッケージについて
http://www.kotha.net/ghcguide_ja/7.0.4/packages.html