Pixel Pedals of Tomakomai

北海道苫小牧市出身の初老の日常

AllowAmbiguousTypes拡張と型適用

このように f を定義して実行したい。

f :: String -> String
f = show . read

main :: IO ()
main = putStrLn $ f "True"

エラーが出る。

Prelude> :l test.hs
[1 of 1] Compiling Main             ( test.hs, interpreted )

test.hs:5:5: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘show’
      prevents the constraint ‘(Show a0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance Show Ordering -- Defined in ‘GHC.Show’
        instance Show Integer -- Defined in ‘GHC.Show’
        instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
        ...plus 22 others
        ...plus 16 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the first argument of ‘(.)’, namely ‘show’
      In the expression: show . read
      In an equation for ‘f’: f = show . read

test.hs:5:12: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘read’
      prevents the constraint ‘(Read a0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance Read Ordering -- Defined in ‘GHC.Read’
        instance Read Integer -- Defined in ‘GHC.Read’
        instance Read a => Read (Maybe a) -- Defined in ‘GHC.Read’
        ...plus 22 others
        ...plus 7 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the second argument of ‘(.)’, namely ‘read’
      In the expression: show . read
      In an equation for ‘f’: f = show . read
Failed, modules loaded: none.

showread の対象とする型 a0 がきちんと決まってないのが原因なので、これを f に対して指定できるようにする。

f :: (Show a, Read a) => String -> String
f = (show :: a -> String) . read

再びエラーとなる。

Prelude> :r
[1 of 1] Compiling Main             ( test.hs, interpreted )

test.hs:4:6: error:
    • Could not deduce (Read a0)
      from the context: (Show a, Read a)
        bound by the type signature for:
                   f :: (Show a, Read a) => String -> String
        at test.hs:4:6-41
      The type variable ‘a0’ is ambiguous
    • In the ambiguity check for ‘f’
      To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
      In the type signature:
        f :: (Show a, Read a) => String -> String
Failed, modules loaded: none.

aShowReadインスタンスだと言ってる割には、型の本文に a が登場しないのでこれを決定する方法がない。 AllowAmbiguousTypes を使うとこのチェックを遅らせられるよと教えてくれているので、有効にする。 が、これまたゴツいエラー。

Prelude> :r
[1 of 1] Compiling Main             ( test.hs, interpreted )

test.hs:5:6: error:
    • Could not deduce (Show a2) arising from a use of ‘show’
      from the context: (Show a, Read a)
        bound by the type signature for:
                   f :: (Show a, Read a) => String -> String
        at test.hs:4:1-41
      Possible fix:
        add (Show a2) to the context of
          an expression type signature:
            a2 -> String
    • In the first argument of ‘(.)’, namely ‘(show :: a -> String)’
      In the expression: (show :: a -> String) . read
      In an equation for ‘f’: f = (show :: a -> String) . read

test.hs:5:29: error:
    • Could not deduce (Read a0) arising from a use of ‘read’
      from the context: (Show a, Read a)
        bound by the type signature for:
                   f :: (Show a, Read a) => String -> String
        at test.hs:4:1-41
      The type variable ‘a0’ is ambiguous
      These potential instances exist:
        instance Read Ordering -- Defined in ‘GHC.Read’
        instance Read Integer -- Defined in ‘GHC.Read’
        instance Read a => Read (Maybe a) -- Defined in ‘GHC.Read’
        ...plus 22 others
        ...plus 7 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the second argument of ‘(.)’, namely ‘read’
      In the expression: (show :: a -> String) . read
      In an equation for ‘f’: f = (show :: a -> String) . read
Failed, modules loaded: none.

これは show :: a -> String が暗黙的に show :: forall a. a -> String と解釈されているのが原因なので、 ScopedTypeVariables 拡張を使う。

{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}

f :: forall a. (Show a, Read a) => String -> String
f = (show :: a -> String) . read

main :: IO ()
main = putStrLn $ f "True"

f の定義についてのエラーはなくなった。後は呼び出し側。

*Main> :r
[1 of 1] Compiling Main             ( test.hs, interpreted )

test.hs:8:19: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘f’
      prevents the constraint ‘(Read a0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance Read Ordering -- Defined in ‘GHC.Read’
        instance Read Integer -- Defined in ‘GHC.Read’
        instance Read a => Read (Maybe a) -- Defined in ‘GHC.Read’
        ...plus 22 others
        ...plus 7 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the second argument of ‘($)’, namely ‘f "True"’
      In the expression: putStrLn $ f "True"
      In an equation for ‘main’: main = putStrLn $ f "True"
Failed, modules loaded: none.

a を指定すればいいのだから、ここで TypeApplications の登場。

{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}

f :: forall a. (Show a, Read a) => String -> String
f = (show :: a -> String) . read

main :: IO ()
main = putStrLn $ f @Bool "True"
Prelude> :r
[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main> :main
True

めでたしめでたし。せっかく TypeApplications を使うなら、 f の定義ももう少し簡潔になる。

f :: forall a. (Show a, Read a) => String -> String
f = show @a . read

余談1. AllowAmbiguousTypes の妥当性

型変数作って TypeApplications 使って適用したいだけなのに突然 AllowAmbiguousTypes 拡張が出てきてなんだよって思ったかもしれないが、 論文中ではこいつの必要性は書いてあって、そもそもは TypeApplications を有効にすると自動的に有効になるようになってた。

このへんのメールのやり取り でない方がいいだろって話になって、 このコミットで消された。

余談2. Proxy

TypeApplications を使えるコンパイラを持っていないあなたでも、型の役割をする式である Proxy 型を使うことができるのだ! 副作用で型の本文に a が入るようになるので、 AllowAmbiguousTypes 拡張も不要になる。

{-# LANGUAGE ScopedTypeVariables #-}

import Data.Proxy

f :: forall proxy a. (Show a, Read a) => proxy a -> String -> String
f _ = (show :: a -> String) . read

main :: IO ()
main = putStrLn $ f (Proxy :: Proxy Bool) "True"

だが、勘がいいあなたなら気がついてしまったかもしれない。 Proxy は可読性をあげてくれるだけで、なくても困らないことを。

{-# LANGUAGE ScopedTypeVariables #-}

f :: forall proxy a. (Show a, Read a) => proxy a -> String -> String
f _ = (show :: a -> String) . read

main :: IO ()
main = putStrLn $ f [False] "True"

余談3. Type defaulting in GHCi

GHCiのデフォルト型の割り当ては強力 なので、なんと f がそのままコンパイルできてしまうのだ!! ただし、勝手に () になってしまう。

*Main> f = show . read
*Main> f "()"
"()"
*Main> f "True"
"*** Exception: Prelude.read: no parse

ConnectionFailure getAddrInfo: does not exist (Name or service not known) が出た

vagrantubuntu/zesty64 を使ったら、 https://github.com/commercialhaskell/stack/issues/2536 的なメッセージが出てかなりの高確率で stack setup に失敗した。

そもそも安定版使ってないほうが悪かったので、 ubuntu/xenial64 使うようにしたら収まった。とは言え、その直前に zesty64 も senial64 もどちらのboxもアップデートされた(20170119.1.0)っぽいので、何が悪かったかは切り分けてない。

2017年センター試験英語

最近ひどく疲れているので http://www.toshin.com/center/ から英語を解いた。リスニングが42点で筆記が169点。おもったよりひどくないと思ってしまったけど、本来満点取らないと駄目なやつだよね、これ。現役の頃を思い出して気分転換にはなったので良しとする。こうやって明確に解法も解答も決まっているのは頭の準備体操にはいいね。

stackのコードを読む(3)

  • リソルバのダウンロード先URLのデフォルトは Stack.Config.Urls で定義されているがコンフィグで上書きできる
  • リゾルバはYAMLでこんな感じで全パッケージとバージョンが書かれてる
packages:
  drawille:
    .. 省略 ..
    version: '0.1.2.0'
    .. 省略 ..
    description:
      cabal-version: '1.10'
      modules:
      - System.Drawille
      provided-exes:
      - image2term
      - senoid
      packages:
        base:
          components:
          - library
          - test-suite
          range: ==4.*
        hspec:
          components:
          - test-suite
          range: ! '>=1.11 && <2.4'
        containers:
          components:
          - library
          - test-suite
          range: ==0.5.*
        QuickCheck:
          components:
          - test-suite
          range: ! '>=2.6'
      tools: {}
  shakespeare:
  .. 省略 ..

ghci 7.10 と 8.0 のレコード記法の違い

DuplicateRecordFields を実装した影響だと思うけど、 ghci で重複するレコード名を定義したときの振る舞いが 7.10 と 8.0 で違ってる。

まず 7.10 。「フィールド定義が消される」という振る舞いに見える。

$ stack --resolver ghc-7.10 ghci
Configuring GHCi with the following packages:
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> data X = X { x :: Bool }
Prelude> data Y = Y { x :: Int }
Prelude> let anX = X { x = True }

<interactive>:18:11:
    Constructor ‘X’ does not have field ‘x’
    In the expression: X {x = True}
    In an equation for ‘anX’: anX = X {x = True}
Prelude> let anX = X { x = 10 }

<interactive>:19:11:
    Constructor ‘X’ does not have field ‘x’
    In the expression: X {x = 10}
    In an equation for ‘anX’: anX = X {x = 10}
Prelude> :t anX

<interactive>:1:1:
    Not in scope: ‘anX’
    Perhaps you meant one of these:
      ‘and’ (imported from Prelude), ‘any’ (imported from Prelude)

8.0 で同じことをやってみる。フィールドがないことを検知してないように思える。気持ち悪いのは、 True を渡すと値を生成できてしまうこと。しかも True はなかったことにされて x フィールドの値を評価すると例外が投げられる。

$ stack ghci
Configuring GHCi with the following packages:
GHCi, version 8.0.1: http://www.haskell.org/ghc/  :? for help
Loaded GHCi configuration from C:\tools\msys64\tmp\ghci1668\ghci-script
Prelude> data X = X { x :: Bool }
Prelude> data Y = Y { x :: Int }
Prelude> let anX = X { x = True }

<interactive>:67:11: warning: [-Wmissing-fields]
    • Fields of ‘X’ not initialised: x
    • In the expression: X {x = True}
      In an equation for ‘anX’: anX = X {x = True}
Prelude> let anX = X { x = 10 }

<interactive>:68:19: error:
    • No instance for (Num Bool) arising from the literal ‘10’
    • In the ‘x’ field of a record
      In the expression: X {x = 10}
      In an equation for ‘anX’: anX = X {x = 10}
Prelude> :t anX
anX :: X
Prelude> let (X x') = anX in x'
*** Exception: <interactive>:3:11-24: Missing field in record construction x

これが起こるのは REPL 上だけで、ソースコード上でフィールド名が重複していれば当然コンパイルが通らないので、大きな問題ではないだろう。そもそも 7.10 系の振る舞いが理想的かってのもある。バグな気はするけど。

stackのコードを読む(2)

stack.yaml はどこで読むのか

Runner.hs#withBuildConfigAndLock なんてのがあって、ここで読んでいる。実際に読んでいるのは Config.hs#loadProjectConfigとかで、こいつが FromJSONのインスタンス になっていてパースしてる。設定の優先順位とかは この辺 で決まってる。設定は Monoid として定義されていて、ほとんどはFirstだが物によっては挙動が違うので注意

Resolver のロード

build を呼ぶお膳立てをしてくれる withBuildConfigAndLock から潜っていくと BuildConfigを読むための関数を作っている。ここで利用する loadBuildConfigBuildPlan#loadResolver の先で ダウンロードなどをしている

用意された lcLoadBuildConfig は buildが呼ばれる前に使われる 。この段階で MiniBuildPlanが決定されて コンパイラのバージョンが決まっている。

stackのコードを読む

stackのコードを読んでるのでメモ。まだ全然肝心なところに入ってない。

  • パーサーでコマンドライン引数をパースしてパースの結果として得られる関数を実行する作り
  • optparse-applicativeをフォークして使っている
    • なんの処理を加えてるのかは読んでない
  • 例えばbuildだと、実際に走る処理は buildCmd となる
  • 例えば buildCmd だと、コマンドのオプションをパースした結果 BuildOptsCLI を元にパース結果として GlobalOpts -> IO () 型の処理を生成して返す (runに束縛される)
  • GlobalOpts のパース結果は addCommand によって作られ、 run という名前で束縛された実際の処理の引数として使われる
  • build コマンドの本命は Stack.Build.build
  • 設定は Config.hs にて継承関係で定義されている
    • 継承関係と言ってるのは、フィールドを用意して明示的に親のデータを持っているという意味
    • Config > BuildConfigNoLocalBuildConfig
    • BuildConfigNoLocalEnvConfigNoLocalEnvConfig
    • ConfigLoadConfig
    • 例えばここに書いたデータ型はすべて HasConfigインスタンスで、 configL というレンズを通して Config のデータに読み書きできる
    • DefaultSignatures拡張による default キーワードを使っている(この拡張、知らなかった)