但此处具有类型bool

但此处具有类型bool

本文介绍了F#编译器错误“该表达式应具有类型单位,但此处具有类型bool。” {if else}语句中的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在F#中编写了这样的函数:

I have written such a function in F#:

let TwistBasket (reverse: bool, quarters: int, overTwist: int byref) =
    overTwist <- 50
    WaitForBasketReady()
    waitBasket.Reset()
    let move = 135*quarters - 25 + overTwist
    let speed =
        match reverse with
            | true -> -75y
            | false -> 75y
    let waitHandle = motorBasket.SpeedProfile(speed, 15u, uint32 move, 10u, true)
    Task.Factory.StartNew(fun () ->
        waitHandle.WaitOne()
        if (overTwist <> 0) then
            motorBasket.SpeedProfile(sbyte -speed, 0u, uint32 overTwist, 0u, true).WaitOne()
        waitBasket.Set()

关于此if语句;

    if (overTwist <> 0) then
         motorBasket.SpeedProfile(sbyte -speed, 0u, uint32 overTwist, 0u, true).WaitOne()

我得到错误:该表达式应具有unit类型,但此处具有bool类型。

实际上 motorBasket.SpeedProfile()。WaitOne()返回布尔值语句。

Actually motorBasket.SpeedProfile().WaitOne()returns boolean statement. I need it.

因为我正在尝试在C#中转换if语句:

Because I'm trying to convert this if else statement in C#:

        Task.Factory.StartNew(() =>
        {
            waitHandle.WaitOne();
            if (overTwist != 0)
            {
                motorBasket.SpeedProfile((sbyte) -speed, 0, (uint) overTwist, 0, true).WaitOne();
            }
            waitBasket.Set();
        });

如何解决我的错误?

推荐答案

通过查看C#版本,它对结果不执行任何操作。因此,在F#中,我将调用 ignore ,它将吃掉结果:

By looking at the C# version, it does nothing with the result. So in F# I would call ignore which will eat the result:

if (overTwist <> 0) then
     motorBasket.SpeedProfile(sbyte -speed, 0u, uint32 overTwist, 0u, true).WaitOne() |> ignore

在这种情况下,如果您的 if .. then 没有 else 分支,其结果应该是单位,这很有意义。

F# is more strict than C# in these cases, if your if .. then has no else branch it result should be unit, which makes perfect sense.

您还可以使用(虚拟)布尔值并将其绑定到(虚拟)值,但是在这种情况下,如果您真的不打算使用该值,那又有什么意义呢?您真正要做的是产生副作用并忽略结果,F#驱动您使其在代码中更明确。

You can also create an else branch with a (dummy) boolean value and let-bind it to a (dummy) value, but in this particular case what's the point if you're really not going to use that value? What you're really doing is creating a side effect and ignoring the result, F# drives you to make it more explicit in your code.

这篇关于F#编译器错误“该表达式应具有类型单位,但此处具有类型bool。” {if else}语句中的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:25