工作需要写了第一个简单的haskell程序,练手

{-# 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,只是为了满足需求

 

转载于:https://my.oschina.net/kylidboy/blog/732896

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值