Haskell的主要功能 [英] Haskell main function

查看:130
本文介绍了Haskell的主要功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 模块Main其中

qsort :: Ord a => [a] - > [a]
qsort [] = []
qsort(x:xs)= qsort小++ [x] ++ qsort大
其中
小= [a | a< -xs,a< = x]
greater = [a | a< -xs,a> x]

main = do qsort [1,3,2]

我得到以下错误:

 无法与实际类型为'[a0]'的预期类型'IO t0'匹配
在表达式中:main
当检查函数`main'的类型时

我做错了吗?

解决方案

do 块中的所有函数都必须匹配返回的monadic值。您可以改为写
$ b $ pre $ $ $ c $ main $ =
print(qsort [1,3,2])

因为 print 会返回 IO 值。同样,如果您使用的是 Maybe monad,则必须执行类似于

   -  lookup :: Eq k => k  - > [(k,v)]  - >也许v 
- listToMaybe :: [a] - >也许是

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

这是可行的,因为 lookup listToMaybe 都返回a Maybe ,它是<$ c $的类型签名所指定的整个 do 块的返回值看看 qsort 的类型,它只返回。 code> [a] ,而不是 IO something ,所以它不能直接在 main 的做块。您还可以使用 let 将其返回值赋值给名称:

  main = do 
let result = qsort [1,3,2]
打印结果


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]

I get the following error

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

What am I doing wrong?

解决方案

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

这篇关于Haskell的主要功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆