工作需要写了第一个简单的haskell程序,练手
2016-08-15 00:00
375 查看
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} module Main where import Options.Applicative import System.Environment import System.Exit import System.IO import System.Directory import System.FilePath import Control.Exception import qualified Data.Map.Lazy as DM -- import qualified Date.ByteString.Lazy as BL import Control.Monad (mapM_) data MyArgs = MyArgs { dir :: FilePath , ref :: FilePath } margs :: Parser MyArgs margs = MyArgs <$> strOption ( long "directory" <> short 'd' <> metavar "DIR" <> help "Directory that contains the downloaded files" ) <*> strOption ( long "reference" <> short 'r' <> metavar "REF" <> help "Reference file that contains the original names and new names" ) renameDownloads :: MyArgs -> IO () renameDownloads MyArgs {..} = do putStrLn $ "Rename maps: " ++ ref putStrLn $ "Source directory: " ++ dir r <- getRenameRef ref fnames <- getDirectoryContents dir let rnMap = DM.fromList r rename dir rnMap fnames putStrLn "Finished" rename :: FilePath -> DM.Map FilePath String -> [FilePath] -> IO () rename dir renameMap = mapM_ rename' where rename' filename = case DM.lookup filename renameMap of Nothing -> return () Just val -> renameFile (dir </> filename) (dir </> val) getRenameRef :: FilePath -> IO [(FilePath, String)] getRenameRef fpath = do h <- openFile fpath ReadMode hSetEncoding h utf8 contents <- hGetContents h parse contents where parse = return . alist . parse' parse' = map words . lines alist = convert2alist . filterValidPath filterValidPath = filter (\inp -> case inp of (x:xs) -> True _ -> False ) convert2alist = map (\(x:xs) -> (x, unwords xs)) main :: IO () main = execParser opts >>= renameDownloads where opts = info (helper <*> margs) ( fullDesc <> progDesc "Batch rename the audio files downloaded from xxxxxxx" )
批量重命名,直接贴代码吧,写ruby的码农朋友说“这他么看也看不懂,是猴子写的吗?”
不得不说,Option.Applicative真心不错,貌似社区也是大力推荐,
没有用monad之类的,基本上就是很简单的逻辑,只是为了习惯了一下haskell的写法,连错误处理没有ADT也没有,所以,just a toy,只是为了满足需求
相关文章推荐
- 最简单的无缝滚动程序,只需要五行代码(转)
- "Hello World", 第一个Haskell程序
- 简单使用Eclipse编写第一个Java程序
- 【糟糕的代码】Android的第一个程序:简单的皮肤更换测试
- 第一个简单的hibernate程序
- 管理是需要的。我是在99年接触csdn的。那时在csdn上看帖子,订程序员杂志,真是感觉获益非浅,由于工作的原因又一段时间没有上csdn。前几天和别的公司程序员聊天,我无意中说道,可以去csdn找找帮助呀,也许程序上的问题就解决了,他的回答让我吃了一惊,c
- 对hadoop第一个小程序WordCount的简单解释.
- ajax 第一个简单程序
- 关于java第一个简单程序错误原因
- 一个班有n个学生,需要把每个学生的简单资料(姓名和学号)输入计算机保存。然后可以通过输入某一学生的姓名查找其有关资料。当输入一个姓名后程序就查找该班有无此学生,如果有,则输出他的姓名和学号,如果找不到
- 配置第一个Struts2的简单登陆程序
- 工作后的第一个程序
- TMS320DM642 EDMA非连续工作简单程序
- 简单使用Eclipse编写第一个Java程序
- [Android] 002_第一个简单的Android程序
- [z]最简单的无缝滚动程序,只需要五行代码
- TMS320DM642 EDMA非连续工作简单程序
- 深入了解汇编的第一个简单程序(对初学者很重要)
- Havok第一个最简单的Hello World程序
- 第一个Java程序,简单的打开图片并显示在面板上