1

我需要在 Ada 中创建一个哈希函数,它接受一个字符串并返回一个整数。到目前为止我所做的是:

function hash(Word: unbounded string) return Integer is
    h := 5381
    c := (first charater of "Word")
begin
    while c /= (end of "Word") loop
         h := h*33 + c;
         c := (next character of "Word");
    end while;
return h mod 20;
end hash;

我不知道如何在 Ada 中选择一个字符,怎么说“我想要单词“word”的第三个字符,即 r。

谢谢你的帮助,

T。

4

3 回答 3

3

查看Ada.Strings.Unbounded包提供的服务。

于 2013-04-05T16:01:38.827 回答
1

As Marc has said, you will need to use Ada.Strings.Unbounded to get at the contents of Word.

There are two other problems you need to address:

  • In Ada, there's no terminating character in an Unbounded_String (or in a String, come to that). Instead, write the loop as for J in 1 .. (length of Word) loop.
  • Once you've extracted the J'th character, it's still a Character and you can't add it to h (I assume h is integral). Character'Pos (Ch) returns the numeric equivalent of the character, and that you can add.
于 2013-04-05T16:24:48.403 回答
1
function hash(Word: Ada.Strings.Unbounded.Unbounded_String) return Integer is
-- First, because there's no manipulation of the string's
-- contents, doing the work on an unbounded-string is
-- rather pointless... so let's do our work on a regular --' fix for formatting
-- [static-length] string.
Working : String := Ada.Strings.Unbounded.To_String(Word);
-- Second, you need types in your declarations.
h : Integer := 5381;
c : Character := 'e'; --(first charater of "Word");
begin
-- Why use a 'while' loop here? Also, what if the 'word' is
-- abracadabra, in that case c [the first letter] is the 
-- same as the last letter... I suspect you want an index.

  for Index in Working'Range loop -- Was: while c /= EOW loop --'
    declare
    -- This is where that 'c' should actually be.
    This  : Character renames Working(Index);
    -- Also, in Ada characters are NOT an integer.
    Value : constant Integer := Character'Pos( This ); --'
    begin
    h := h*33 + value; -- PS: why 33? That should be commented.
    -- We don't need the following line at all anymore. --'
    --c := (next character of "Word");
    end;        
  end loop;
return h mod 20;
end hash;

当然,这也可以重写以利用 Ada 2012 中的新循环结构。

function hash_2012(Word: Ada.Strings.Unbounded.Unbounded_String) return Integer is
    -- Default should be explained.
    Default : Constant Integer := 5381;
    Use Ada.Strings.Unbounded;
begin
    -- Using Ada 2005's extended return, because it's a bit cleaner.
    Return Result : Integer:= Default do
        For Ch of To_String(Word) loop
            Result:= Result * 33 + Character'Pos(Ch); --'
        end loop;

        Result:= Result mod 20;
    End return;
end hash_2012;

...我不得不问,格式化程序发生了什么?这太可怕了。

于 2013-04-05T18:25:25.570 回答