簡體   English   中英

如何設置Haskell的GHCI以交互式評估函數到其簽名(類型)而不是出錯?

[英]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在提示符下報告類型錯誤的內容。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM