Skip to content

Instantly share code, notes, and snippets.

@iain17
Created April 6, 2017 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iain17/2a8194bfcee28974d2f30ae778b5326d to your computer and use it in GitHub Desktop.
Save iain17/2a8194bfcee28974d2f30ae778b5326d to your computer and use it in GitHub Desktop.
Assignment: Consider a list of keyword-value tuples, such as [{erlang, "a functional language"}, {ruby, "an OO language"}]. Write a function that accepts the list and a keyword and returns the associated value for the keyword.
- module(key_lookup).
- export([search/2]).
%Assignment: Consider a list of keyword-value tuples, such as [{erlang, "a functional language"}, {ruby, "an OO language"}]. Write a function that accepts the list and a keyword and returns the associated value for the keyword.
search(Key, List) -> do_search(Key, List).
%With the use of pattern matching we are able to have the do_search1 return once we
%hit the result.
do_search(Key, [{Key, Value}|_]) ->
io:fwrite("do_search1 Keyword(~p) Value(~p)\n", [Key, Value]),
Value;
%This one keeps on calling itself. Taking the tail till it hits the above method.
do_search(Key, [_|T]) ->
io:fwrite("do_search2 Keyword(~p) Tail(~p)\n", [Key, T]),
do_search(Key, T).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment