所以我正在尝试学习 Elixir(我有 F# 和 Haskell 的背景),但我很难理解我的代码中发生的事情:
fizz_buzz = fn
(0, 0, _) -> "FizzBuzz"
(0, _, _) -> "Fizz"
(_, 0, _) -> "Buzz"
(_, _, c) -> c
end
fizz_buzz_rem = fn n -> fizz_buzz.(rem(n, 3), rem(n, 5), n) end
# This works
IO.puts(fizz_buzz_rem.(10))
IO.puts(fizz_buzz_rem.(11))
IO.puts(fizz_buzz_rem.(12))
IO.puts(fizz_buzz_rem.(13))
IO.puts(fizz_buzz_rem.(14))
IO.puts(fizz_buzz_rem.(15))
IO.puts(fizz_buzz_rem.(16))
IO.puts(fizz_buzz_rem.(17))
IO.puts("----------------")
inputs =
10..17
|> Enum.to_list
# Doesn't work
inputs
|> Enum.map(fizz_buzz_rem)
|> IO.puts
IO.puts("----------------")
# Doesn't work
inputs
|> Enum.map(fn n -> fizz_buzz.(rem(n, 3), rem(n, 5), n) …Run Code Online (Sandbox Code Playgroud) 我刚刚开始学习Clojure,并且尝试模拟Monty Hall问题:
(defn create-contest
"Creates a monty hall doors contest"
[n]
(do (def door-with-car (rand-int n))
(map
(fn [i] (if (= i door-with-car) :car :closed))
(range n))))
(defn create-doors
"Create a collection of monty hall contests"
[doors contests]
(doall
(map
(fn [i] (create-contest i))
(repeat contests doors))))
Run Code Online (Sandbox Code Playgroud)
但是,每次执行该create-doors功能时,所有带有轿厢的门都位于同一位置:
broker.core> (create-doors 4 10)
((:car :closed :closed :closed)
(:car :closed :closed :closed)
(:car :closed :closed :closed)
(:car :closed :closed :closed)
(:car :closed :closed :closed)
(:car :closed :closed :closed) …Run Code Online (Sandbox Code Playgroud)