すぐに忘れるので、参照先

  • Haskellの「入門サイト」とかは、「形式」についてが多くて、「あれってどうやるんだっけ?」というghciに戻ってくるとき(このghciの綴りすらうまく思い出せないような、そんな事態のとき)には役に立たない
  • そんなレベルで「とりあえず、参照」するには、
    • 必要なことが小さくまとまっている
    • コピーペーストでうまく行く(let で定義している行をひたすら、自分のhoge.hsファイルにコピーペーストしていき、それをghciでロード(:l hoge.hs)したうえで、letのついていない行の実行内容をghci上でプロンプトに打ち込む)
  • の2つが必要
  • そんな基準で20分ウェブサーチをして、最善と判断したのがこちら
  • ここのをコピペして、作ったファイルmymains.hsが以下で、それを実行する方法は3通り
  • 実行方法3通り
    • (1) ghciを使う
ghci
      • と打って、その中から
:l mymains.hs
      • と打って、読み込み、
      • 関数(main,main1,main2,e,add 3 4とか)を実行する
      • また、":t add",":t Tree"とかやって、定義を覗く
    • (2) コンパイルして実行する
    • (3) コマンドプロンプトからrunghcする
      • runghc mymains.hsとやるとこれもmain関数を実行する
main = main3
main1 = putStrLn "Hello, World!" -- コメントです

{- {- 複数行コメントアウトは{- -}です。-}
Haskellではいくらネストしても問題ありません。 -}

--{- 複数行コメントアウトのコメントアウトです。
main2 = putStrLn "Hello?"
---}

e = exp 1
str = "moge"
str2 = ['1','2','3']
arr = [1,2,3]
str3 = str2 ++ str
main3 = putStrLn str3
main4 = putStrLn (str ++ str2)

tpl1 = ( 1, "one" )   -- (Int,String)型
data Bool = False | True    deriving (Eq, Ord, Show)
data Maybe a = Nothing | Just a   deriving (Eq, Ord, Show)
data Tree = Empty | Node Int Tree Tree
add :: Int -> Int -> Int
add a b     = a + b

factorial :: Int -> Int
factorial 0     = 1
factorial n     = n * factorial (n - 1)

map :: ( a -> b ) -> [a] -> [b]
map _ []         = []
map f (x:xs)     = f x : map f xs

func :: (Int, String, [Bool]) -> String
func (n, s, [])         = show n ++ s ++ "Empty list"
func (n, s, (b:bs))     = show n ++ s ++ show b

absolute :: (Num a, Ord a) => a -> a
absolute a | a < 0        = -a
           | otherwise    = a
  • importが出てきたらファイルを変える
    • "test.hs"とする。入力ファイル"input.txt"を読み込むと書いてあるのでそのようなファイルも作っておく(小文字を大文字にするプログラムなのでアルファベットで書いておく
-- test.hs
import System.IO
import Data.Char(toUpper)

main = do
       inh <- openFile "input.txt" ReadMode  -- 読み込みでinput.txtを開く
       outh <- openFile "output.txt" WriteMode -- 書き込みでoutput.txtを開く
       inpStr <- hGetContents inh          -- ハンドラから取り出す
       hPutStr outh (map toUpper inpStr)   -- ハンドラに渡す
       hClose inh  -- ファイルを閉じる
       hClose outh  -- ファイルを閉じる
      • input.txt
repao koewoja

 aeoarj ga
 s
    • 作成されるoutput.txt
REPAO KOEWOJA

 AEOARJ GA
 S