In my job search, I was issued a coding challenge last week, and needed to learn the basics of several languages I’m not familiar with. I’m not sure they use some of those regularly on the job – seems they just wanted to see if I could flexibly catch on.
The challenges themselves were very easy to solve. The first one was a slightly modified FizzBuzz challenge in Haskell, and the second one was spotting palindromes, and sorting text, in each of the other 3 languages.
One thing that stuck out to me was the differences/similarities of taking a file path as a command line argument in Rust, Python, and Swift.
In Rust, you need std::env, std::fs::File, and std::fs::BufReader. Then you can grab your arguments and put them into an array, and then select the path from the array, open the file, and read it, like this:
1 2 3 4 |
let args: Vec<_> = env::args().collect(); let filepath = &args[1]; let f = File::open(filepath).unwrap(); let file = BufReader::new(&f); |
In Python you only need to import sys, and you can do the following:
1 2 3 |
filepath = sys.argv[1] with open(filepath) as fp: for num, line in enumerate(fp): |
Then under that, you can say what you want to do for each line in that file. I implemented the same behavior in Rust, but took more code than I showed in the above example. In Python, it’s much simpler, so it’s included here.
Finally, in Swift, it’s somewhere in between. I did the following to collect the argument I wanted:
1 2 3 4 5 |
private let arguments: [String] public init(arguments: [String] = CommandLine.arguments) { self.arguments = arguments } |
Then within a public func, I had this:
1 2 3 4 5 6 7 8 9 |
let fileName = arguments[1] do { let contents = try NSString(contentsOfFile: fileName, encoding: String.Encoding.ascii.rawValue) contents.enumerateLines({ (line, stop) -> () in *CODE FOR EACH LINE HERE* }) } |
It took a bit of time to figure out the ins and outs of how to do this in each language, but lucky for me, reading individual lines from a file is pretty commonly done in all languages. I was able to read a lot of explanations on how other people have done it, and why they did it that way. No one I saw was trying to do the same thing I was, but reading lines from a file can be pretty universal! I’m glad for all the great documentation online – especially when learning to use a new programming language.