Ghciを使用して、Haskellを初めて使用します。
threeという名前の関数があり、次のように書きたい
let three = \x->(\y->(x(x(x y))))
OK、これは機能しますが、試してみると
three (2+) 4
それは動作しません。代わりに、「無限型を構築できません」というエラーが表示されます。
私を助けてください。
ghci> let three = \x->(\y->(x(x(x y))))
ghci> three (2+) 4
10
ghci> three return "deconstructivist"
<interactive>:1:6:
Occurs check: cannot construct the infinite type: t = m t
Expected type: t
Inferred type: m t
In the first argument of 'three', namely 'return'
In the expression: three return "deconstructivist"
ghci> :t three
three :: (t -> t) -> t -> t
ghci> :t return
return :: (Monad m) => a -> m a
three (2+) 4
! 提供する例が実際に問題を再現することを確認してください。return
、指定されたものとは異なるタイプの結果が返されるということです。* -> * -> * -> ...
型が同じなら、それはHaskell がサポートしていない無限 (および種類) になります。あなたが与える例はうまくいきます。理由を説明しましょう:
three f = f . f . f
-- so...
three :: (a -> a) -> a -> a
関数は型a -> a
を必要とする独自の引数を受け取るため、型が必要です。(2+)
typeNum a => a -> a
を持っているので、three (2+) 4
問題なく動作します。
ただし、別の型を返す type のような関数を渡すと、設定した要件に一致しませreturn
ん。これは、関数が失敗する場所と時期です。Monad m => a -> m a
(a -> a)
その間、与えられた関数を与えられた回数実行するdoTimes
with typeのような関数を作ってみてください- これはこの関数を作った後の良い次のステップです。Integer -> (a -> a) -> a -> a