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))