Home > database >  How can I run this function when it can work on CMD
How can I run this function when it can work on CMD

Time:11-01

module Examples where 
   import System.Random
   import Data.List
   cars = ["Ferrari", "Audi", "Honda","McLaren","Merc"]
   cmp (x1,y1) (x2,y2) = compare y1 y2
   [car | (car, n) <- sortBy cmp(zip cars (randoms (mkStdGen 123456) :: [Int]))]

I keep getting this error:

Parse error: module header, import declaration or top-level declaration expected. | 7 | [car | (car, n) <- sortBy cmp(zip cars (randoms (mkStdGen 123456) :: [Int]))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :reload

Does anyone have any idea for me to fix this so this function can run

CodePudding user response:

Your list comprehension is not a function, it is an expression defined at the top level, which makes not much sense. You can define a main that prints the result for example:

module Examples where 
  import System.Random
  import Data.List
  
  cars :: [String]
  cars = ["Ferrari", "Audi", "Honda","McLaren","Merc"]
  
  cmp :: Ord b => (a, b) -> (a, b) -> Ordering
  cmp (x1,y1) (x2,y2) = compare y1 y2

  main :: IO ()   
  main = print [car | (car, n) <- sortBy cmp(zip cars (randoms (mkStdGen 123456) :: [Int]))]
  • Related