I tried the code below , whereas the M1 is the Map consists of M1= #{a =>"Apple",b =>"Ball"}, and Str is the given by user ex: fun("ab").
I want to print the relevant value of the key in Map M1 based on the given string Str.
Tried Code:
fun(Str) ->
X = [ [X] || X <- Str],
Key = maps:keys(M1),
mOrse_convert(X,Key)
end;
mOrse_convert([],Key) ->
true;
mOrse_convert([First|Rest],Key) ->
case Key of
#{ X := A} -> A
end
mOrse_convert(Rest,Key)
end.
Can anyone help/suggest me ?
4条答案
按热度按时间vbkedwbf1#
This function has 2 arguments:
Str
- value to find and targetMap
. The function returns list of all keys in Map that have value equalsStr
.Go to Erlang shell and type following command:
bf1o4zei2#
Thank you Alexei , the solution provided by you is working good for an alphabet and got the output only for single character and given below, but I want to pass the List as input in as Str , I tried the below code as List as input,
Output for single alphabet :
My Required output is :
Tried Code :
qlfbtfca3#
In the shell:
An erlang string, e.g.
"abc"
, is actually a shortcut for creating a list of integers, where each integer is the ascii code of a letter in the string. For example:When the shell outputs a string, the shell expects you to know that the string is really a list of integers, which is confusing. To eliminate that confusion, you can tell the shell not to output strings by executing the function
shell:strings(false)
:Then you can see what you are really dealing with.
Next, when you use pattern matching to remove an integer from a list, you have an integer--not a string. To create a string from an integer, you need to put the integer into a list:
You can see that here:
It's not clear whether you have atoms or strings as the keys in your map or whether you don't care. If your map must have atoms as the keys, you can convert strings to atoms using
list_to_atom/1
:Finally, when you want to output a string, e.g. one of the values in the map, rather than a list (after executing
shell:strings(false)
), you can use the~s
formatting sequence:Using a list comprehension would look like this:
A list comprehension always returns a list, in this case
[ok, ok, ok]
, which is not something you care about--you only care about the side affect of outputting the values. So, you can ignore the list and return something else, i.e. whateverio:format/1
returns, which isok
.Remember, it's less confusing to have the shell output lists rather than strings, then only output strings when you specifically tell the shell to do it.
4urapxun4#
我不确定是否理解您的要求,这里有两种解释。