gpt4 book ai didi

Haskell主要函数

转载 作者:行者123 更新时间:2023-12-02 06:33:32 27 4
gpt4 key购买 nike

module Main where

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

main = do qsort [1,3,2]

我收到以下错误

Couldn't match expected type `IO t0' with actual type `[a0]'         
In the expression: main
When checking the type of the function `main'

我做错了什么?

最佳答案

do block 中的所有函数都必须与返回的一元值匹配。你可以改为写

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

因为print返回一个IO值。同样,如果您使用 Maybe monad,则必须执行类似的操作

-- 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

这是可行的,因为 lookuplistToMaybe 都返回一个 Maybe,它是整个 do 的返回值> 由 firstElementOf 的类型签名指定的 block 。

qsort的类型,它只返回[a],而不是IO some,所以不能直接使用在 main 的 do block 内。您还可以使用 let 将其返回值分配给名称:

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

关于Haskell主要函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26474892/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com