Haskell main function

后端 未结 1 1003
醉话见心
醉话见心 2021-02-19 23:24
module Main where

qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort (x : xs) = qsort smaller ++ [x] ++ qsort larger
                 where
                   small         


        
1条回答
  •  暖寄归人
    2021-02-19 23:47

    All functions within a do block must match the monadic value being returned. You could instead write

    main = do
        print (qsort [1, 3, 2])
    

    Because print returns an IO value. Similarly, if you were using the Maybe monad, you would have to do something like

    -- lookup :: Eq k => k -> [(k, v)] -> Maybe v
    -- listToMaybe :: [a] -> Maybe a
    
    firstElementOf :: Eq q => k -> [(k, [v])] -> Maybe v
    firstElementOf key assocMap = do
        v <- lookup key assocMap
        first <- listToMaybe v
        return first
    

    This works because lookup and listToMaybe both return a Maybe, which is the return value of the overall do block as specified by the type signature of firstElementOf.

    Looking at the type of qsort, it only returns [a], not IO something, so it can't be used directly inside main's do block. You could also assign it's returned value to a name using let:

    main = do
        let result = qsort [1, 3, 2]
        print result
    

    0 讨论(0)
提交回复
热议问题