简体   繁体   English

定义返回类型IO [a] Haskell

[英]Define return type IO [a] Haskell

I want to return the expected type IO [a] 我想返回预期的IO类型[a]

I tried: Type that I want 我试过了:我想要的类型

fc :: [a] -> IO [a]
fc a = sequence $ map show list

> fc [1,2,3]
> [1,2,3]

What can I do? 我能做什么?

If you have a pure value, the way to convert to into a monadic value is with the return (aka pure ) function: 如果您有一个纯值,则转换为单值的方法是使用return (aka pure )函数:

fc :: [a] -> IO [a]
fc list = return list

But if you want to map the show function over your list, the result will be [String] , because the function show :: a -> String turns any value into a String , so: 但是,如果要将show函数映射到列表中,结果将为[String] ,因为函数show :: a -> String会将任何值转换为String ,因此:

fc :: Show a => [a] -> IO [String]
fc list = return $ map show list

Notice the Show a constraint. 注意Show a约束。 It tells the compiler that the type a , whatever it is, must support function show . 它告诉编译器,无论类型a是什么,都必须支持show函数。 Without it, such function won't type check. 没有它,该功能将无法进行类型检查。

The sequence function is beside the point completely, since it turns a list of monadic values into one monadic value that is a list. sequence函数完全位于该点的旁边,因为它将单价值列表转换为一个单价值列表。 If you wanted to use that function, then the list you pass to it must be a list of monadic values, for example: 如果要使用该函数,则传递给它的列表必须是单子值列表,例如:

fc :: Show a => [a] -> IO [()]
fc list = sequence $ map print list

Here, print is an IO () action that prints out a value. 在这里, print是一个IO ()操作,它打印出一个值。

If you want a more precise answer, you'd need to specify more clearly what you're trying to do. 如果您想要更精确的答案,则需要更明确地指定要执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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