Last active
August 29, 2015 14:07
-
-
Save ppurang/4f81d31e38c8673b4882 to your computer and use it in GitHub Desktop.
count chars in a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// see also http://piyush.purang.net/blog/Reading_Type_Signatures_5e999531-595f-4348-b44c-e239be962885 | |
import java.io.File | |
// following is the goal | |
type CountCharsInAFile = String => Int | |
type PathToFile = String => File | |
def pathToFile : PathToFile = new File(_) | |
type FileToLines = File => List[String] | |
def fileToLines: FileToLines = io.Source.fromFile(_).getLines.to[List] | |
type CountCharsInLines = List[String] => List[Int] // we can decompose this further into type CountCharsInALine = String => Int | |
def countCharsInLines: CountCharsInLines = x => x.map(y => y.to[List].length+1) // the +1 counts line break chars that `getLines` above looses. Will fail if two chars represent a line break. | |
type Total = List[Int] => Int | |
def total: Total = _.sum | |
//bring the parts together | |
def countCharsInAFile: CountCharsInAFile = (total compose countCharsInLines compose fileToLines compose pathToFile)(_) | |
// or alternatively | |
def countCharsInAFile2: CountCharsInAFile = x => total(countCharsInLines(fileToLines(pathToFile(x)))) // hmm '_' instead of 'x' didn't work under 2.11.1 | |
//use them | |
countCharsInAFile("somechars.txt") | |
countCharsInAFile2("somechars.txt") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment