[英]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.