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

统计一段英文文章中不同单词出现的次数,用F#写着玩玩,纯属娱乐!嘿嘿

使用二叉树,中序遍历输出;调用.NET 的File.ReadAllText读取文件

 

module node
//二叉树 ,Node为节点,Empty为空节点
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
 
//递归插入节点,节点为空则插入新节点,若比节点数据data大,则插入其右子节点,若比他小,则插入其左节点
//若等于,则将节点的num加一,表明这个单词又出现一次
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 " )
//以空格分割文件中的内容,得到单词string数组
let strings = reader.Split( ' ' )
//定义可变的root
let mutable root = node.Empty
//遍历所有单词,构造二叉树
for s in strings do
root
<- node.insert1 (s, 1 ,root)
 //中序遍历,输出统计内容
node.printTree root
0

转载于:https://www.cnblogs.com/xiwang/archive/2011/06/23/xiwang.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值