LoginSignup
34
29

More than 5 years have passed since last update.

ghciでの関数定義

Posted at

関数プログラミング入門の最初のコードでいきなり躓いたのでメモ。

ghciは一行ずつ処理するため、以下のような関数を作りたいときにちょっとはまりました。

square.hs
square :: Int -> Int
square x = x * x

これを直接ghciで打とうとすると一行目のコードを打っておちますし、letをつけても二行目に辿りつけないのでやはりだめ。
で、どうやるかっていうので3パターンほど調べました。

:set +m

ghciで複数行扱えるモードにしてしまうパターンです。

% ghci
Prelude> :set +m
Prelude> let square :: Int -> Int
Prelude| square x = x * x

<interactive>:5:1: parse error on input `square'
Prelude> let square :: Int -> Int
Prelude|  square x = x * x

<interactive>:7:2: parse error on input `square'
Prelude> let square :: Int -> Int
Prelude|     square x = x * x
Prelude|
Prelude> square 3768
14197824

注意点としては、定義する関数のインテントをあわせる必要があります。

:{ :} で囲む

複数行モードにすると面倒なこともあるので、専用の囲むやつを使うという手があります。
こっちもインデントに注意。

% ghci
Prelude> :{
Prelude| let square :: Int -> Int
Prelude| square x = x * x
Prelude| :}

<interactive>:6:1: parse error on input `square'
Prelude> :{
Prelude| let square :: Int -> Int
Prelude|     square x = x * x
Prelude| :}
Prelude> square 3768
14197824

ちょっとカワイイ(何

複数行を一行にまとめる

; を使って複数行をまとめるという方法もあります。ワンライナーっぽさありますね。

% ghci
Prelude> let square :: Int -> Int; square x = x * x
Prelude> square 3678
13527684

とりあえずここらへん抑えればghci使って勉強していくのにはなんとかなりそう。
でも、ソースファイル書いた方が楽そうな気配もある...

34
29
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
34
29