代码改变世界

(转)F# 统计一段英文文章中不同单词出现的次数

2011-06-23 23:02  音乐让我说  阅读(418)  评论(0编辑  收藏  举报

转载自:http://www.cnblogs.com/xiwang/archive/2011/06/23/xiwang.html

统计一段英文文章中不同单词出现的次数

 使用二叉树作为存储结构,中序遍历输出;调用.NET 的File.ReadAllText读取文件

module node
type Tree =  Empty | Node of Tree * string * int * Tree 
let rec printTree t=
	match t with 
	| Empty -> printfn "  "
	| Node(l,data,num,r) as n ->
	 printTree l
	printfn "%s ---次数是----- %d" data num
	printTree r

let rec insert1 = function
	| x ,n, Empty -> Node(Empty,x,1,Empty)
	| x ,n, Node(l ,data,num,r) -> 
	if x <data then Node(insert(x,1,l),data,num,r)
	 elif x > data then Node( l ,data,num,insert(x,1,r))
	else Node(l,data,num+1,r)


open System
open System.IO
[<EntryPoint>]
let main (args : string[]) =
let reader =File.ReadAllText("D:\\s.txt")
let strings = reader.Split(' ')
let mutable root = node.Empty
for s in strings do
root <- node.insert1 (s,1,root)
node.printTree root
0

 

谢谢浏览!