How to apply higher order function to an effectful function in Haskell?

前端 未结 2 825
礼貌的吻别
礼貌的吻别 2020-12-16 00:50

I have too functions:

higherOrderPure :: (a -> b) -> c
effectful :: Monad m => (a -> m b)

I\'d like to apply the first function

2条回答
  •  萌比男神i
    2020-12-16 01:19

    I think you can achieve what you want by writing a monadic version of curve:

    curveM :: Monad m => (Double -> m Double) -> m (QDiagram B R2 Any)
    curveM f = do
        let xs = [1..100]
        ys <- mapM f xs
        let pts = map p2 $ zip xs ys
        return $ fromVertices pts
    

    This can easily be written shorter, but it has the type you want. This is analogous to map -> mapM and zipWith -> zipWithM. The monadic versions of the functions have to be separated out into different implementations.


    To test:

    func1, func2 :: Double -> Either String Double
    func1 x = if x < 1000 then Right x else Left "Too large"
    func2 x = if x < 10   then Right x else Left "Too large"
    
    > curveM func1
    Right (_ :: QDiagram B R2 Any)
    > curveM func2
    Left "Too large"
    

提交回复
热议问题