I want to return the expected type 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:
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:
fc :: Show a => [a] -> IO [String]
fc list = return $ map show list
Notice the Show a
constraint. It tells the compiler that the type a
, whatever it is, must support function 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. 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.
If you want a more precise answer, you'd need to specify more clearly what you're trying to do.
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.