windows - Recursive function call hanging, Erlang -


i teaching self erlang. going until found problem function.

-module(chapter). -compile(export_all).  list_length([])      ->   0; list_length([_|xs])  ->   1+list_length([xs]). 

this taken out of textbook. when run code using otp 17, hangs, meaning sits shown below.

1> c(chapter). {ok,chapter} 2> chapter:list_length([]). 0 3> chapter:list_length([1,2]). 

when looking in task manager erlang otp using 200 mb 330 mb of memory. causes this.

it not terminating because creating new non-empty list in every case: [anything] non-empty list, if list contains empty list member ([[]] non-empty list of 1 member).

a proper list terminates this: [ | [] ].

so in mind...

list_length([])      ->   0; list_length([_|xs])  ->   1 + list_length(xs). 

in functional languages "proper lists" cons-style lists. check out the wikipedia entry on "cons" , the erlang documentation lists, , meditate on examples of list operations see written in example code bit.

notes

  1. putting whitespace around operators thing; prevent doing confused stuff arrows , binary syntax operators next each other along avoiding few other ambiguities (and easier read anyway).

  2. as steve points out, memory explosion noticed because while function recursive, not tail recursive -- is, 1 + list_length(xs) leaves pending work done, must leave reference on stack. have add 1 must complete execution of list_length/1, return value, , in case remember pending value many times there members in list. read steve's answer example of how tail recursive functions can written using accumulator value.


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -