22
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Haskellで外部モジュールを使いたいとき(モジュールimportとパッケージinstall)

Last updated at Posted at 2020-02-14

モジュール名とパッケージ名

Haskellにおいて外部モジュールを使用するにはimportでモジュール名を宣言する。

import.hs
import System.Random

Data.Charのような代表的な幾つかのモジュールは、環境構築時にあらかじめローカル環境に導入されているのでimportするだけで、すぐ使えるようになる。
しかし、ローカル環境に導入されていないパッケージを使用するにはimportの前にinstallが必要になる。

このときinstallコマンドに指定しなければならないのは、モジュール名ではなくパッケージ名である。

たとえば、乱数を扱うモジュールの名称はSystem.Randomであるが、パッケージの名称はrandomなので、install時はrandomを指定する必要がある。

install.hs
> :t random
<interactive>:1:1: error: Variable not in scope: random
-- random関数を使いたい。が、そんなものはないと言われる

> :m System.Random
<no location info>: error:
    Could not find module System.Random
    It is not a module in the current program, or in any known package.

-- random関数の含まれるSystem.Randomモジュールをimportしようとしたが知らないと言われてしまう

> stack install random
random> configure
random> Configuring random-1.1...
random> build
random> Building random-1.1...
random> Preprocessing library random-1.1...
random> [1 of 1] Compiling System.Random    ( System\Random.hs, .stack-work\dist\ca59d0ab\build\System\Random.o )
random>
random> C:\Users\xx\AppData\Local\Temp\stack3120\random-1.1\System\Random.hs:43:1: warning: [-Wtabs]
random>     Tab character found here, and in 74 further locations.
random>     Please use spaces instead.
random> copy/register
random> Installing library in
random> C:\sr\snapshots\47914953\lib\x86_64-windows-ghc-8.0.2\random-1.1-9tceXaeYIMZ4JrKq20Egog
random> Registering random-1.1...
-- パッケージ名randomを指定してinstall

> :m System.Random
> :t random
random :: (RandomGen g, Random a) => g -> (a, g)
-- random関数が使えるようになった

Haskellを始めてから、しばらくコレが分からなくて苦労した。(何てったって、これが分からないと乱数すら使えない)

モジュールとパッケージの関係は、こんな感じで確認できる。

使いたい関数名等からパッケージ名を調べる

今使いたい乱数を生成する関数randomをHoogleなどでサーチして
image.png

モジュールのドキュメントに遷移する。今回はSystem.Randomである。
image.png

その上部にある囲みの部分がパッケージ名。
したがってinstallするときにはcabal install randomなりstack install randomとする。

パッケージ名からモジュール名を調べる

逆にパッケージ名のドキュメントからモジュール名を確認するには、同様にパッケージ名からパッケージのドキュメントに遷移してimage.png

Modulesを確認する。

22
8
1

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
22
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?