I'm gonna be short.
I'm going through exercism exercises.
At one moment I had a beef with the compiler.
The 4th and 5th branches of this if produce different types of values.
4| if x == 'G' then
5| 'C'
6| else if x == 'C' then
7| 'G'
8| else if x == 'T' then
9| 'A'
10| else if x == 'A' then
11| 'U'
12| else
13|> "There is an Unknown Character in the DNA sequence!!!"
The 4th branch has this type:
Char
But the 5th is:
String
Hint: All the branches of an if need to match so that no matter which one we
take, we get back the same type of value overall.
To me, it seemed unreasonable :)
Now, I'm just stuck here.
The definition of toRNA does not match its type annotation.
17| toRNA : String -> Result Char String
18| toRNA dna =
19|> converted_to_list dna
20|> |> List.map convert
21|> |> String.fromList
The type annotation for toRNA says it always returns:
Result Char String
But the returned value (shown above) is a:
String
Detected errors in 1 module.
Top comments (8)
You have a fundamental representation problem:
you should not use a
Charto describe a nucleotide base. Allowed values are onlyA,C,TandG. With this representation it could also beZor;...Instead, create a new type:
or you can also use
A | T | G | Cfor brevity if that does not conflict with anything.That way you will not have to consider incorrect values because they cannot exist.
Also consider using a
case x ofrather than multipleifs.First, I'm gonna try deal wit the case and then with the Result type and then I will add types.
P.S. I just got my hand on frondendmasters elm courses. I will postpone solving the problem. Want to watch the videos first.
You won't need
Resultin this case if you make impossible state impossible :-)BTW, have you tried the official Elm documentation? I'm not sure how they hold up for people new to functional programming but I myself found them sufficient (for the fundamentals anyway).
The exercise is written such that it expects to get a
Result.github.com/exercism/elm/blob/maste...
I would argue this isn't a good exercise then. There are better way to explain result, that do not promote improper state representation (such as making a safe division function).
I apologize for being harsh. I understand writing this stuff is time-consuming and sometimes hard, but I do believe this (making impossible state impossible) is an important concept, central to Elm and FP in general.
Consider rewriting those conditionals as a
casestatement. Then make the return of thecasestatement a Result type.Now all arms are the same type and the compiler won't complain.
I wanted to use case, but then I wondered if elm has if else expression. So I didn't get to the case.
Thanks for pointing out to the Result type. I didn't know that exists.
I believe case statements are considered more idiomatic in elm.