Elixir简单的wordcount小程序
程序员文章站
2022-06-05 15:26:46
...
本文来自:fair-jm.iteye.com 转截请注明出处
defmodule Wordcount do @moduledoc "simple wordcount program by fairjm" @nodecount 3 def start(file) do s = self spawn(fn -> count(file,s) end) end defp count(file,caller) do s = self nodes = Enum.map(1..@nodecount,fn _e -> spawn(fn -> countLine end) end) count = File.stream!(file) |> Enum.reduce(0,fn e,r -> send(Enum.at(nodes,:random.uniform(@nodecount)-1),{e,s});r+1 end) IO.puts("total count is #{count}") v = countDown(count,%{}) nodes |> Enum.each(&(send(&1,Stop))) send(caller,v) end defp countDown(0,m) do IO.puts("ending") m end defp countDown(n,m) do receive do map -> countDown(n-1, Enum.reduce(map,m,fn {k,v},r -> Map.put(r,k,Map.get(r,k,0)+v) end)) after 5000 -> countDown( n-1 , m) end end defp countLine do receive do {line,caller} -> IO.puts("#{inspect(self)} is doing work") m = line |> String.strip |> String.split(" ") |> Stream.filter(&(String.length(&1) > 0)) |> Enum.reduce(%{},fn e,r -> case r[e] do nil -> Map.put(r,e,1) v -> Map.put(r,e,v+1) end end ) send(caller,m) countLine Stop -> IO.puts("#{inspect(self)} quits") _other -> IO.puts("error message") countLine end end end
简单的小练习 代码中用三个erlang进程模拟mapper 一个进程模拟reducer
elixir的语法比erlang的要平易近人好多
有兴趣学的同学 推介买一本elixir in action(http://www.manning.com/juric/)
或者图灵社区有爱的同学整理的教程: http://www.ituring.com.cn/minibook/10831
此外这位同学的github上也维护着中文学习资料: https://github.com/elixir-lang-cn/programming-elixir