[erlang-questions] how to make beautifulll code of this working code
Joe Armstrong
erlang@REDACTED
Mon Aug 10 20:46:46 CEST 2015
On Mon, Aug 10, 2015 at 8:34 PM, Roelof Wobben <r.wobben@REDACTED> wrote:
> Thanks for the tip.
My pleasure.
Another tip.
When I'm writing functions I often just write a function clause that I
know will crash. For example
date_parts(Date) ->
L = string:tokens(Date,"-"),
[my_to_int(I) || I <- L].
my_to_int(a) ->
1.
Then I run this and it will crash. But the shell will print the argument that
my_to_int was called with. Then I cut and paste this into the function head.
Often I'm not 100% sure what arguments a function will be called with, so
I just put dummy arguments a,b,c etc. that will cause the program to crash.
Then I run test cases and fix the crashing cases - so the order in
which the code is developed depends upon how it is crashing.
Its a run->crash->fix cycle. It's almost like TDD I'd call it CDD
(Crash Driven Development)
Cheers
/Joe
>
> Op 10-8-2015 om 20:29 schreef Joe Armstrong:
>
>> On Mon, Aug 10, 2015 at 6:09 PM, Roelof Wobben <r.wobben@REDACTED> wrote:
>>>
>>> Op 10-8-2015 om 17:59 schreef Garry Hodgson:
>>>>
>>>> date_parts(Date) ->
>>>> [list_to_integer(N) || N <- string:tokens(Date,"-")].
>>>
>>>
>>> When testing I see this output:
>>>
>>> 2> dates:date_parts("2012-02-02").
>>> ** exception error: bad argument in function list_to_integer/1 called
>>> as
>>> list_to_integer(<<"2012">>) in call from
>>> dates:'-date_parts/1-lc$^0/1-0-'/1
>>> (dates.erl, line 6)
>>
>> If you're a beginner it might be helpful to not combine function calls
>> but to write the code with intermediate variables like this:
>>
>> date_parts(Date) ->
>> L = string:tokens(Date,"-"),
>> [list_to_integer(I) || I <- L].
>>
>> That way you can add print statements to see what's going on
>> like this:
>>
>> date_parts(Date) ->
>> L = string:tokens(Date,"-"),
>> io:format("L=~p~n",[L]),
>> [list_to_integer(I) || I <- L].
>>
>> As you become more experienced you'll omit the temporary variables
>> because you'll *know* what they should be. But when you're beginning
>> make each line of code do as little as possible and print the results to
>> check your understanding.
>>
>> Poke each line into the shell to see what's happening.
>>
>> /Joe
>>
>>
>>>
>>> ---
>>> Dit e-mailbericht is gecontroleerd op virussen met Avast
>>> antivirussoftware.
>>> https://www.avast.com/antivirus
>>>
>>> _______________________________________________
>>> erlang-questions mailing list
>>> erlang-questions@REDACTED
>>> http://erlang.org/mailman/listinfo/erlang-questions
>
>
>
> ---
> Dit e-mailbericht is gecontroleerd op virussen met Avast antivirussoftware.
> https://www.avast.com/antivirus
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
More information about the erlang-questions
mailing list