読者です 読者をやめる 読者になる 読者になる

Haskellのお勉強 文字列の扱い

プログラム

今日はwcとexprを実装してみた
wcは文字数と行数だけ
exprは結合規則はめんどいのでやんぴ

wc

main = do
	contents <- getContents
	putStr "line_count = "
	putStrLn $ show $ line_count $ lines contents
	putStr "char count = "
	putStrLn $ show $ char_count $ lines contents


line_count :: [String] -> Int
line_count [] = 0
line_count (x:xs) = 1 + line_count xs


char_count :: [String] -> Int
char_count [] = 0
char_count (x:xs) = chars x + char_count xs
	where
		chars :: String -> Int
		chars []     = 0
		chars (x:xs) = 1 + chars xs

length使わずにごりごりやってみた

expr

import System.Environment

main = do
	args <- getArgs
	putStrLn $ show $ expr args

expr :: [String] -> Int
expr []  = 0
expr [x] = read x
expr (left:ope:xs)
	| ope == "+" = (read left) +     (expr xs)
	| ope == "-" = (read left) -     (expr xs)
	| ope == "*" = (read left) *     (expr xs)
	| ope == "/" = (read left) `div` (expr xs)

右優先結合only

明日のお題はcsv読み書き
明後日のお題はタプルで1要素目を元にsum、count(group byするイメージ)
明々後日は今月のデータを抽出する方法