Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a list from a function?

Tags:

haskell

I have this function in Haskell to get perfect numbers. I want to return a list of perfect numbers.

perfect :: Int -> []
perfect digit  = [presentNum | presentNum <- [1..digit], isPerfect presentNum]

isPerfect :: Integer -> Bool   --function declaration 
isPerfect n =  n == sum [i | i <- [1..n-1], n `mod` i == 0]

but I am met with the error

  • Expecting one more argument to []' Expected a type, but[]' has kind `* -> *'
  • In the type signature: perfect :: Int -> []

How do I properly return a list?

like image 558
Oto-obong Eshiett Avatar asked Aug 05 '26 15:08

Oto-obong Eshiett


1 Answers

You have to specify the type of the list elements:

perfect :: Int -> [Int]
                -- ^^^ --

There is no type of "lists" [], but only types such as "list of integers" [Int], "list of strings" [String] and so on.

Technically, Haskell does allow [] as a type constructor of kind * -> * (that's what the error reports), making [] not a type but something that takes a type like Int and returns a type [Int]. So, roughly, [] is a function from types to types, not a type.

like image 123
chi Avatar answered Aug 08 '26 20:08

chi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!