Define the executable entry point main only in the file that cabal's main-is points to (app/Main.hs for a single executable), keep library modules free of main, and expose a function such as run for Main.hs to call. Use when writing or reviewing Haskell executables, cabal executable stanzas, or where to put main.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Main Module?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/ncaq-main-module)
---
name: main-module
description: Define the executable entry point main only in the file that cabal's main-is points to (app/Main.hs for a single executable), keep library modules free of main, and expose a function such as run for Main.hs to call. Use when writing or reviewing Haskell executables, cabal executable stanzas, or where to put main.
user-invocable: false
---
# `main`は`main-is`が指すファイルだけに置く
実行ファイルのエントリポイントの`main`は、
cabalの`main-is`が指すファイルだけに置いてください。
実行ファイルが1つなら`app/Main.hs`です。
`src/`以下のライブラリのモジュールには`main :: IO ()`を書きません。
処理の本体は`run`のような関数としてライブラリから公開し、
`Main.hs`から呼び出します。
以下のような入口の仕事を、1箇所にまとめるためです。
- コマンドライン引数や環境変数の受け取り。
- ロガーなどの実行環境の構築。
- 上位まで伝播した例外の最終的な処理と、終了コードの決定。
入口の仕事が分かれていると、
どこで引数を読み、どこでロガーを設定しているのかを探すことになります。
ライブラリの関数は引数と環境を受け取るだけになるので、
テストからも実行環境を差し替えて直接呼び出せます。
## 書き方
`Main.hs`には入口の仕事だけを書き、処理の本体は書きません。
例えばhimariを使う場合は以下のようになります。
```haskell
module Main (main) where
import Foo.Cli (run)
import Himari
main :: IO ()
main = runSimpleEnv (getArgs >>= run)
```
cabalファイルでは、ライブラリと実行ファイルのソースのディレクトリを分けます。
```cabal
library
hs-source-dirs: src
exposed-modules: Foo.Cli
executable foo
hs-source-dirs: app
main-is: Main.hs
build-depends: base, foo, himari
```
1つのパッケージに複数の実行ファイルがある場合は、
`app/<実行ファイル名>/Main.hs`のように実行ファイルごとにディレクトリを分けます。
`ghc-options`の`-main-is`で、ライブラリのモジュールの関数をエントリポイントにすることもしません。
テストスイートのエントリポイントも同じ考えで、
`main-is`が指すファイルだけに`main`を置きます。