在Array中搜索2个值,彼此相邻

Mat*_* Ad 3 f# functional-programming

我正在解决我在C#中解决的问题的解决方案,但现在我将我的代码移植到F#.我有一个字节数组,我需要在这个数组中搜索两个值(x,y).当我找到时x,需要检查:如果y是下一个索引,我们有匹配.如果y不在下一个索引上,搜索将继续.我该如何解决这个问题?我试图使用Array.findIndex,但没有成功,因为我不知道如何继续搜索时y不在下一个索引.

编辑:

public void GetValue(byte[] data)
        {
            byte[] temp = new byte[4];
            for (int i = 0; i < data.Length; i++)
            {
                if (data[i] == Adress[0] && data[i + 1] == Adress[1])
                {
                    for (int j = 0; j < temp.Length; j++)
                    {
                        temp[j] = data[j + i + 2];
                    }
                    Value = BitConverter.ToInt32(temp, 0) * 0.01;
                    break;
                }

            }
Run Code Online (Sandbox Code Playgroud)

s95*_*163 9

您可以轻松地将其变为功能:

let bytes = [| 104uy; 101uy; 108uy; 108uy; 111uy |]

bytes 
|> Array.pairwise
|> Array.findIndex (fun x -> fst x = snd x)
//2
Run Code Online (Sandbox Code Playgroud)

  • 我会解构对'fun(x,y) - > x = y`而不是使用`fst`和`snd`. (3认同)
  • This solution is what i wanted. Im amazed how clean solution can be in functional programming (2认同)
  • @MateuszAd - 如果此答案帮助您解决问题,则应单击分数下的复选标记以将其标记为已接受.这使得在搜索中找到您的问题的其他人知道它被正确回答,因此如果他们有相同的问题,他们将能够找到答案. (2认同)