How to flatten IO [[String]]?

前端 未结 2 749
失恋的感觉
失恋的感觉 2020-12-18 06:14

I am new to Haskell and have some difficulties wrapping my head around some of it\'s concepts.

While playing around with IO I wanted to flatten an IO [[String]].

2条回答
  •  没有蜡笔的小新
    2020-12-18 06:28

    You can't get anything "out" of IO, so what you need to do is lift flatten to work inside it. The simplest way to do this is fmap--just like map applies a function over a list, fmap applies a function over any Functor instance, such as IO.

    flattenIO xs = fmap flatten xs
    

    In more general cases, you can use do notation to get at things in IO computations. For example:

    flattenIO xs = do ys <- xs
                      return (flatten ys)
    

    ...which is just a roundabout way of writing fmap in this case.

提交回复
热议问题