3

I'm trying to make a function that takes an a (which can be any type: int, char...) and creates a list which has that input replicated the number of times that corresponds to its ASCII code.

I've created this:

toList n = replicate (fromEnum n) n

When trying to use the function in the cmd it says it could match the expected type int with char, however if i use my function directly in the cmd with an actual value it does what it's supposed.

What i mean is: toList 'a' --> gives me an error

replicate (fromEnum 'a') 'a' --> gives a result without problem

I've loaded the module Data.Char (ord)

How can I fix this, and why does this happens?

Thanks in advance :)

4

1 回答 1

4

您缺少的是类型声明。您说您希望它能够采用任何类型,但您真正想要的是toList采用Enum. 当您在 GHCi 中使用它时,它会让您这样做let toList n = replicate (fromEnum n) n,因为 GHCi 会自动选择一些似乎有意义的默认值,但是当使用 GHC 编译模块时,如果没有类型声明,它将无法工作。你要

toList :: (Enum a) => a -> [a]
toList n = replicate (fromEnum n) n

您必须(Enum a) =>在类型签名中具有 的原因是因为fromEnum具有类型签名(Enum a) => a -> Int。所以你看到它不只是采用任何类型,只有那些具有Enum.

于 2013-09-28T16:07:19.550 回答