So, I’ve started to work on these exercises but using Elixir: https://courses.calhoun.io/courses/cor_gophercises
specifically, the first one:
Part 1 Create a program that will read in a quiz provided via a CSV file (more details below) and will then give the quiz to a user keeping track of how many questions they get right and how many they get incorrect. Regardless of whether the answer is correct or wrong the next question should be asked immediately afterwards.
and
Part 2 Adapt your program from part 1 to add a timer. The default time limit should be 30 seconds, but should also be customizable via a flag. Your quiz should stop as soon as the time limit has exceeded. That is, you shouldn’t wait for the user to answer one final questions but should ideally stop the quiz entirely even if you are currently waiting on an answer from the end user. Users should be asked to press enter (or some other key) before the timer starts, and then the questions should be printed out to the screen one at a time until the user provides an answer. Regardless of whether the answer is correct or wrong the next question should be asked. At the end of the quiz the program should still output the total number of questions correct and how many questions there were in total. Questions given invalid answers or unanswered are considered incorrect.
So my Part 1 implementation is this:
defmodule CsvQuiz do
@moduledoc """
Documentation for CsvQuiz.
"""
def csv_quiz(path) do
[i, s] =
parser(path)
|> Enum.reduce([0, 0], fn array, [iteration, acc] ->
solution(array, iteration, acc) end)
IO.puts("\nYou scored #{s} of #{i}.")
System.halt()
end
defp parser(path) do
File.read!(path)
|> String.split("\n")
|> Enum.reject(fn x -> x == "" end)
|> Enum.map(&String.split(&1, ","))
end
defp solution([question, answer], iteration, acc) do
num = iteration + 1
input = IO.gets("Problem ##{num}: #{question} = ") |> String.trim()
result =
if input == answer do
acc + 1
else
acc
end
[num, result]
end
end
and that is how to run it and what I have as an output:
❯ iex -S mix
Erlang/OTP 22 [erts-10.4.1] [source] [64-bit]
[smp:12:12] [ds:12:12:10] [async-threads:1] [hipe]
Compiling 1 file (.ex)
Interactive Elixir (1.9.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> CsvQuiz.csv_quiz("/gophercises_in_elixir/lib/1_csv_quiz_problems.csv")
Problem #1: 5+5 = 10
Problem #2: 1+1 = 2
Problem #3: 8+3 = 11
Problem #4: 1+2 = 3
Problem #5: 8+6 = 1
Problem #6: 3+1 = 1
Problem #7: 1+4 = 1
Problem #8: 5+1 = 1
Problem #9: 2+3 = 1
Problem #10: 3+3 = 1
Problem #11: 2+4 = 1
Problem #12: 5+2 = 1
You scored 4 of 12.
But I am stuck with Part 2, I mean not about the code itself, but about what tools do I need to use?
Could you please critic my Part 1
and suggest where to move according to Part 2 description.
I guess I need to use Task.yield()
but I am not sure to be honest.
Thanks a lot in advance!