Search code examples
haskellhaskell-turtle

Convert String to Turtle.FilePath


How can I convert a concatenated String to a Turtle FilePath? For instance, the following program tries to read some text files, concatenate them into a new one and remove the old ones. It does not seem to work although the OverloadedStrings extension is enabled:

{-# LANGUAGE OverloadedStrings #-}

module Main where

import System.Environment
import System.IO
import Control.Monad
import Turtle
import Turtle.Prelude
import qualified Control.Foldl as L

main :: IO ()
main = do
  params <- getArgs
  let n             = read $ params !! 0
      k             = read $ params !! 1
  -- Some magic is done here
  -- After a while, read generated .txt files and concatenate them
  files <- fold (find (suffix ".txt") ".") L.list
  let concat = cat $ fmap input files
  output (show n ++ "-" ++ show k ++ ".txt") concat
  -- Remove old .txt files
  mapM_ rm files

The error thrown is:

Couldn't match expected type ‘Turtle.FilePath’
                with actual type ‘[Char]’
    In the first argument of ‘output’, namely
      ‘(show n ++ "-" ++ show k ++ ".txt")’

Switching to output "example.txt" concat would just work fine. Isn't String just a type alias of [Char]?


Solution

  • String is just an alias to [Char], yes.

    You see the bit where it says {-# OverloadedStrings #-}? What that does is make the compiler automatically insert fromString everywhere you write a literal string. It does not automatically insert it anywhere else you touch a string, only when it's a string constant.

    If you manually call fromString on the result of the whole expression for building the path, that will probably fix it. (In particular, the show function always returns String, not any kind of overloaded string.)