elixirs / elixirs/faker

Utilities for non-deterministic data generation

Open
#433 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Elixir
Stars
1.2k
Forks
261
Avg merge
2d 16h
Merged PRs (30d)
13

Description

I've written the following *very simple* utility macro to generate proabilistic fake data for a project and thought other people might find it interesting. It doesn't make sense to package such a simple macro but it might make sense to include it in a larger package such as `Faker`. The implementation speaks for itself:

```elixir
defmodule ProbabilityDemo do
defmacro with_probability(p, [do: do_body, else: else_body]) do
quote do
if :rand.uniform() < unquote(p) do
unquote(do_body)
else
unquote(else_body)
end
end
end
end
```

You use it like this

```elixir
iex(2)> import ProbabilityDemo
ProbabilityDemo
iex(3)> with_probability 0.3 do "Success!" else "Failure!" end
"Failure!"
iex(4)> with_probability 0.3 do "Success!" else "Failure!" end
"Failure!"
iex(5)> with_probability 0.3 do "Success!" else "Failure!" end
"Failure!"
iex(6)> with_probability 0.3 do "Success!" else "Failure!" end
"Failure!"
iex(7)> with_probability 0.3 do "Success!" else "Failure!" end
"Failure!"
iex(8)> with_probability 0.3 do "Success!" else "Failure!" end
"Failure!"
iex(9)> with_probability 0.3 do "Success!" else "Failure!" end
"Failure!"
iex(10)> with_probability 0.3 do "Success!" else "Failure!" end
"Success!"
iex(11)> with_probability 0.3 do "Success!" else "Failure!" end
"Success!"
```

It saves you from writing something like the following and makes the intent clearer

```elixir
# Is the first outcome success or failure? should it be < or >?
if :rand.uniform() < prob do
# something in case of success
else
# something in case of failure
end
```

In practice I'm using it for things like:

```elixir
gender = with_probability 0.35 do :female else :male end
```

What do you think about including something like this in Faker?

Contributor guide

Open the contributing guide

Research direction

No files, tests, or entry points are named. Start by evaluating the supplied Elixir macro and whether Faker should provide a probability helper; done would require an agreed API and tests, neither of which the issue specifies.

Written by the indexing model from the issue text.

Assessment

Tech stack
elixir
Domain
data, testing
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.