[英]I am getting different results when running my Haskell code interactively using ghci and when loading it as a module
[英]How can I set up Haskell's GHCI to interactively evaluate functions to their signature (type) instead of getting errors?
要在Haskell GHCI中查看函数的签名,我必须在其前面添加:t
:
Prelude> f = \x -> x+1
Prelude> :t f
f :: Num a => a -> a
但是每次输入这个前缀都会很快变旧。 如果我把它遗漏,我会收到错误:
Prelude> f
<interactive>:5:1: error:
• No instance for (Show (a0 -> a0)) arising from a use of ‘print’
(maybe you haven't applied a function to enough arguments?)
• In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
我想看到一些关于我的函数f
有用信息,而不是得到这个错误信息:tf
(可能更多关于f
信息)。
如何设置GHCI以实现此功能,即在输入时获取功能信息而不:t
?
GHCi已经很高兴地向您展示您在提示中键入的任何类型,选项为:set +t
。 唯一的问题是在事物上调用show
,并且没有适当的方式来显示函数 - 并且只为可以以有效方式显示的表达式打印类型。 但是,你可以很容易地解决这个问题:
>newtype ShowType a = ShowType a
newtype ShowType a = ShowType a
>instance Show (ShowType a) where show _ = "The type is"
>:set +t
>ShowType const
The type is
it :: ShowType (a -> b -> a)
不幸的是,这会产生很多语法噪音。 我首选的解决方案是将以下内容添加到.ghci
文件中:
:set +t
instance {-# OVERLAPS #-} Show a where show _ = "The type is"
将这样的Show
实例添加到任何真正的Haskell模块将是一个严重的错误,但在.ghci
模块中,它只覆盖在提示符中输入的表达式,所以对我来说似乎没问题。 有了这个,你得到:
>const
The type is
it :: a -> b -> a
>show
The type is
it :: Show a => a -> String
方便的是,当你有一个类型“技术上”有效但具有不可满足约束的函数时,你仍然会得到一个类型错误:
>:t \x -> x `div` (x / x)
\x -> x `div` (x / x) :: (Integral a, Fractional a) => a -> a
^^^^^^^^^^^^^^^^^^^^^^^^^^
>\x -> x `div` (x / x)
<interactive>:12:1: error:
* Ambiguous type variable `a0' arising from a use of `it'
prevents the constraint `(Fractional a0)' from being solved.
但是,绝对最简单的解决方案是:set +t
并在表达式为非Show
时给出一个let
语句:
>let _f = show
_f :: Show a => a -> String
不幸的是,如果左侧是通配符 - let _ = show
- 则不打印该类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.