Wednesday, February 6, 2013

Yield Bang is similar to Ruby's multiple assignment

(In learning from "Programming F# 3.0, 2nd Edition")

Yield Bang ( yield! ) is similar to Ruby's multiple assignment.

In Ruby (multiple assignment)

require 'pathname'

def all_file_under(pathname)
  pathname.each_child.find_all(&:directory?).reduce(pathname.each_child.find_all(&:file?)) do |accum, subpathname|
    accum = Array[*accum, *all_file_under(subpathname)]
  end
end

puts all_file_under(Pathname.new('C:\temp'))
C:\temp/AAAAA
C:\temp/BBBBBB
C:\temp/CCCCCCC
C:\temp/DDD/EEEE
...

In F# (Yield Bang)

> open System.IO;;
> let rec allFilesUnder basePath =
-     seq {
-         yield! Directory.GetFiles(basePath)
-         for subdir in Directory.GetDirectories(basePath) do
-             yield! allFilesUnder subdir
-     };;

val allFilesUnder : basePath:string -> seq<string>

> allFilesUnder @"C:\temp";;
val it : seq<string> =
  seq
    ["C:\temp\AAAAA"; "C:\temp\BBBBBB";
     "C:\temp\CCCCCCC"; "C:\temp\DDD\EEEE"; ...]

No comments:

Post a Comment