Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function length "a" does not compile, if OverloadedStrings extension is enabled

Tags:

haskell

If "{-# LANGUAGE OverloadedStrings #-}" is included at the top of the source file, or in package.yaml (I am using stack), then

length "a"  -- does not compile anymore.

However the custom function length' is working fine

length' :: [a] -> Int 
length' xs = sum [1 | _ <- xs] 

The package Data.String is imported - I think the problem is there, but, I am interested to see, if somebody had similar problem.

Stack and GHC versions: Version 2.3.1, Git revision x86_64 hpack-0.33.0, ghc-8.8.3

I am using mac osx, but the same error is in Linux and windows too.

This is an error produced by stack:

/Users/admin1/Haskell/PROJECTS/orig1/src/Lib.hs:13:29: error:
    • Ambiguous type variables ‘t0’,
                               ‘a0’ arising from the literal ‘"a"’
      prevents the constraint ‘(IsString (t0 a0))’ from being solved.
      Probable fix: use a type annotation to specify what ‘t0’,
                                                          ‘a0’ should be.
      These potential instances exist:
        instance (a ~ Char) => IsString [a] -- Defined in ‘Data.String’
        ...plus two instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the first argument of ‘length’, namely ‘"a"’
      In the first argument of ‘show’, namely ‘(length "a")’
      In the second argument of ‘($)’, namely ‘show (length "a")’
   |
13 |     putStrLn $ show (length "a")  -- does not work, if "- OverloadedStrings" is on  
like image 919
Forestshield Avatar asked Oct 22 '25 23:10

Forestshield


1 Answers

This is because length has a signature length :: Foldable f => f a -> Int, so it can be any Foldable type. If you use the OverloadedStrings extension, then "foo" is no longer a String, it can be any type IsString a => a, and multiple fo these can be Foldable f => f as as well.

What you can do is give the compiler a type hint, for example with:

length ("a" :: String)
like image 113
Willem Van Onsem Avatar answered Oct 25 '25 19:10

Willem Van Onsem