简体   繁体   中英

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)

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 () names)

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

import Data.List()

main = print ( snd names)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM