Why can't Haskell function return a list

Question

What is wrong with that:

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

Error :

<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

Show source
| haskell   2017-10-04 21:10 1 Answers

Answers to Why can&#39;t Haskell function return a list ( 1 )

  1. 2017-10-04 21:10

    I can't give a complete answer without seeing the full extent of what you're doing, but here's one definite problem that is almost certainly involved. You write

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

    The type of floor is

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

    The type of (-) is

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

    Since you use a - floor a, you're forcing the type of a to be an instance of both the RealFrac class and the Integral class. However, there is no such type in the standard library (and it doesn't make a lot of sense). As a result, GHC certainly will not be able to select the type for you from its very limited collection of defaults. Things might work out a lot better if you use

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

    But note that it doesn't really make much sense to have a list here, since you're trying to divide a number into two components of different types. You might be better off with

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

Leave a reply to - Why can't Haskell function return a list

◀ Go back