haskell - 为什么 Haskell 函数不能返回一个列表

标签 haskell

这有什么问题:

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

最佳答案

如果不了解您正在做的事情的全部内容,我无法给出完整的答案,但这里有一个几乎肯定涉及的明确问题。你写

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

floor 的类型是

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

(-)的类型是

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

由于您使用了 a - floor a,因此您强制 a 的类型成为 both 的实例RealFrac Integral 类。但是,标准库中没有这样的类型(而且它没有多大意义)。因此,GHC 肯定无法从其非常有限的默认值集合中为您选择类型。如果你使用,事情可能会好很多

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

但请注意,这里有一个列表并没有多大意义,因为您正试图将一个数字分成两个不同类型的部分。你可能会过得更好

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

关于haskell - 为什么 Haskell 函数不能返回一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46572775/

相关文章:

haskell - (++) 惰性求值的性能

haskell - 如何在 nix 中从 haskell 包(使用 stack/cabal)构建可执行文件?

list - 在 Haskell 中压缩

list - Haskell 函数将列表中的元素相乘

haskell - 通过并发提高仿真性能

haskell - 如何快速轻松地为 Emacs 配置 GHC 集成?

haskell - 如何将本地版本的库与 cabal 链接

performance - Haskell Warp Performance vs Erlang Misultin 测试(如何加载文件内容一次并提供响应)

haskell - 递归方案允许递归调用之间的依赖关系(有序变形?)

haskell - 为什么 ghc 警告 ^2 需要 "defaulting the constraint to type ' Integer'?