解开一个 monad [英] Unwrapping a monad

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

问题描述

鉴于下面的程序,我在处理 monad 时遇到了问题.

Given the below program, I am having issues dealing with monads.

module Main 
where
import System.Environment
import System.Directory
import System.IO
import Text.CSV

--------------------------------------------------

exister :: String -> IO Bool
exister path = do
  fileexist <- doesFileExist path 
  direxist  <- doesDirectoryExist path
  return (fileexist || direxist )

--------------------------------------------------
slurp :: String -> IO String 
slurp path = do
  withFile path ReadMode (handle -> do
                             contents <- hGetContents handle
                             last contents `seq` return contents )
--------------------------------------------------    
main :: IO ()
main = do
  [csv_filename] <- getArgs
  putStrLn (show csv_filename)
  csv_raw <- slurp csv_filename
  let csv_data = parseCSV csv_filename csv_raw

  printCSV csv_data -- unable to compile. 

csv_data 是一个(解析错误)CSV 类型,printCSV 只接受 CSV 数据.

csv_data is an Either (parseerror) CSV type, and printCSV takes only CSV data.

这是工作版本和损坏版本之间的区别.

Here's the ediff between the working version and the broken version.

***************
*** 27,30 ****
    csv_raw <- slurp csv_filename
    let csv_data = parseCSV csv_filename csv_raw

!   printCSV csv_data -- unable to compile. 
 No newline at end of file
--- 27,35 ----
    csv_raw <- slurp csv_filename
    let csv_data = parseCSV csv_filename csv_raw

!   case csv_data of 
!     Left error -> putStrLn $ show error
!     Right csv_data -> putStrLn $ printCSV csv_data
!     
!   putStrLn "done"
!       

参考:http://hackage.haskell.org/packages/archive/csv/0.1.2/doc/html/Text-CSV.html

推荐答案

使用case.

main = do
    ...
    case csv_data of
        Left  err -> {- whatever you're going to do with an error -- print it, throw it as an exception, etc. -}
        Right csv -> printCSV csv

either 函数更短(在语法上),但归结为相同的东西.

The either function is shorter (syntax-wise), but boils down to the same thing.

main = do
    ...
    either ({- error condition function -}) printCSV csv_data

这篇关于解开一个 monad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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