Search code examples
listsortinghaskellghci

Haskell -> Printing sortBy list - error: parse error on input ‘print’


I was trying to run this program on ghci, where it reorders the names in the ascending order of their last names. However, when I run it, I get this error " error: parse error on input ‘print’ ".
I would truly appreciate it if you can help me out with this. Thank you![enter image description here][1]

import Data.List

main :: IO ()

names = [("Tatsunori", "Ono"), ("Kishore", "Palanisamy"), ("Calder", "Hosgood"), ("Yiling", "Zhuang")]

main = do
 let compareLastNames name1 name2 = if lastName1 > lastName2
                                      then GT
                                      else if lastName1 < lastName2
                                            then LT
                                            else EQ
   where lastName1 = snd name1
         lastName2 = snd name2
   
   print (sortBy compareLastNames names)

Solution

  • The reason is the where that is indented at the same level of the let, and not more indented than the compareLastNames function.

    You can indent this with:

    main = do
        let compareLastNames name1 name2 = if lastName1 > lastName2 then GT else if lastName1 < lastName2 then LT else EQ
                where lastName1 = snd name1
                      lastName2 = snd name2
        print (sortBy compareLastNames names)

    But you make this too complicated, you can work with on :: (b -> b -> c) -> (a -> b) -> a -> a -> c:

    import Data.Function(on)
    
    main = print (sortBy (compare `on` snd) names)

    or use sortOn :: Ord b => (a -> b) -> [a] -> [a]:

    import Data.List(sortOn)
    
    main = print (sortOn snd names)