Вопрос

I tried to check this stackoverflow answer with ghci and get the following error:

> import Data.List
> let m = head . sort
> m [2,3,4]

<interactive>:5:4:
   No instance for (Num ()) arising from the literal `2'
   Possible fix: add an instance declaration for (Num ())
   In the expression: 2
   In the first argument of `m', namely `[2, 3, 4]'
   In the expression: m [2, 3, 4]

Unfortunately I cannot reproduce the error in a written haskell file:

-- file.hs
import Data.List

main = do
    let m = head . sort
    putStrLn $ show $ m [2,3,4]

Running this file with runhaskell file.hs gives me the expected value 2. What is my mistake in the ghci session?

Edit: I noted, that the function m has a weird type in ghci:

> import Data.List
> let m = head . sort
> :t m
m :: [()] -> ()

Why is this the case? Shouldn't it has the type Ord a => [a] -> a? For sort and head I get the expected types:

> :t sort
sort :: Ord a => [a] -> [a]
> :t head
head :: [a] -> a
Это было полезно?

Решение

This is the fault of the dreaded Monomorphism restriction. Basically, because you didn't specify a type for m, GHCi guesses it for you. In this case, it guesses that m should have the type [()] -> (), even though that is clearly not what you want. Just give m a type signature in GHCi and you'll be fine.

> :set +m  -- multiline expressions, they're handy
> let m :: Ord a => [a] -> a
|     m = head . sort

You can disable the Monomorphism restriction with

> :set -XNoMonomorphismRestriction

But it's usually pretty handy, otherwise you have to specify lots of types for things that you normally wouldn't in interactive mode.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top