2017-10-04 51 views
1

什麼是錯的:爲什麼不能哈斯克爾函數返回一個列表

partin a = [floor a, a-floor a] 

錯誤:

<interactive>:342:1: error: 
    • Ambiguous type variable ‘a0’ arising from a use of ‘print’ 
     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 a stmt of an interactive GHCi command: print it 
+4

這是在說打印的東西,但你不顯示你如何打印東西。請顯示你正在做的事情的其餘部分。 – dfeuer

+0

其實當我做「part a = a - floor a」也是同樣的錯誤。代碼只包含這個函數 –

+3

他只是在GHCi提示符處輸入'part something',按照簽名行「在交互式GHCi命令的語句中:'打印它」。 – HTNW

回答

7

我不能給出一個完整的答案沒有看到的你的充分程度我們正在做,但這是一個肯定涉及的問題。你寫

partin a = [floor a, a-floor a] 

類型的floor

floor :: (RealFrac a, Integral b) => a -> b 

類型的(-)

(-) :: Num a => a -> a -> a 

由於您使用a - floor a,你這是在強迫的a類型爲一個實例RealFracIntegral類。但是,標準庫中沒有這種類型(並且它沒有多大意義)。因此,GHC肯定無法從其非常有限的默認值中爲您選擇類型。事情都有可能制定出好多了,如果你使用

partin a = [fromIntegral (floor a), a - fromIntegral (floor a :: Int)] 

但是請注意,它並沒有真正太大的意義有列表這裏,因爲你想了許多分爲不同的兩個組成部分類型。你可能會更好

partin a = (floor a, a - fromIntegral (floor a :: Int))