Erlang on Windows List Comprehension multiply give

2019-03-04 18:44发布

Hi i have a weird problem with Erlang on Windows i am running 16B and WinXP.

I have the following code

-module(test).
-export([cost/1,total/1]).
cost(orange) ->
    5;
cost(apple) ->
    6.

total(L) ->
    [cost(I) * Q || {I,Q} <- L].

I run it with

test:total([{orange,2}]).

and it gives me "\f"

changing cost(I) * Q to use -,+ or divide gives me a number.

I have no idea why multiply dosen't work in list comprehension. Running

[test:cost(I) * Q || {I,Q} <- [{orange,2}]]

in an erlang console and emacs mode also dosen't work but

test:cost(orange) * 2

does give me a number.

Any ideas why?

2条回答
▲ chillily
2楼-- · 2019-03-04 19:07

Note your cost/1 function returns a number. But total/1 returns a list (of numbers). The results on that list are ok, this is just how erlang happens to display lists of small integers. See http://www.erlang.org/faq/problems.html 9.3

to see what I mean, try with larger numbers

test:total([{orange,2000}]).

Again, this is just a display issue, the value in the lists are what you expect. Try it:

[Value] = test:total([{orange,2}]).
Value.
查看更多
看我几分像从前
3楼-- · 2019-03-04 19:31

A string is a list of integers. The value you're returning is a list of integers.

Erlang uses a simple heuristic for when to show something as a string, or as a list of integers: is it a flat list containing only numbers in the range {55,250}. (I made those numbers up, but it's something like that. If there are control characters or low characters, it bails.)

Since Erlang doesn't do this to tuples, tuples make it easy to see.

1> {72,101,108,108,111,44,32,83,116,101,112,104,101,110,46}.
{72,101,108,108,111,44,32,83,116,101,112,104,101,110,46}

2> [72,101,108,108,111,44,32,83,116,101,112,104,101,110,46].
"Hello, Stephen."

Erlang is just guessing wrongly what's inside the list.

HTH.

查看更多
登录 后发表回答