【问题标题】:F#: Type mismatch error when trying to count number of lowercase letters in a stringF#:尝试计算字符串中小写字母的数量时出现类型不匹配错误
【发布时间】:2018-09-27 02:54:54
【问题描述】:

所以我正在尝试计算字符串中小写字母的数量。像这样:

intput: "hello world"
output: 10

这就是我所拥有的:

let lowers (str : string) : int  = 
  let count  = 0
  for i=0 to (str.Length-1) do
    if (Char.IsLower(str.[i])) then (count = count+1)
    else count
  printf "%i" count

但我不断收到此错误:

 All branches of an 'if' expression must have the same type. This expression was expected to have type 'bool', but here has type 'int'.

我花了好几个小时试图解决这个问题,但一点进展也没有。我怎样才能打印出我拥有的计数值?它还说:

expecting an int but given a unit

请帮忙

【问题讨论】:

    标签: count f# type-mismatch


    【解决方案1】:

    在 F# 中,变量默认是不可变的。这意味着您不能为它们分配新值:count = count+1 并不意味着“取 count 的值,将其加 1,然后将新值分配给 count”,就像在其他语言中所做的那样。相反,= 运算符(当它不是 let x = ... 声明的一部分时)是 comparison 运算符。所以count = count+1 表示“true 如果count 等于count 加一,或者false 如果两个值不相等”。当然,这总是错误的。

    您正在尝试执行的操作,为变量分配新值,使用 <- 运算符,并要求首先声明变量 mutable

    let mutable count = 0
    count <- count + 1
    

    所以你的代码需要看起来像这样:

    let lowers (str : string) : int  = 
      let mutable count = 0
      for i=0 to (str.Length-1) do
        if (Char.IsLower(str.[i])) then count <- count+1
      count
    

    要注意的另一件事是我删除了else count 行。 if...then...else 表达式的两边必须具有相同的类型,并且变量赋值的类型是“无类型”,F# 将其称为 unit,原因我不会在这里讨论,因为最好在学习新知识时一次只关注一个概念。此外,还有更好的方法(例如某些内置函数)来计算字符串中匹配某个条件的字符数,但同样,一次一个概念。

    更新:我忘了提及您的代码需要的另一项更改。您已将 lowers 函数声明为返回一个 int 值,但原始代码的最后一行是 printf "%d" count,它返回“nothing”(称为 unit 的类型)。这就是“期望一个 int 但给定一个单位”错误的来源。要返回count 的值,您的代码的最后一行需要是简单的count:F# 函数的返回值是函数中最后一个表达式的值。这里是count 的值,所以函数中的最后一个表达式必须是简单的count 行,这样就成为函数的返回值。

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2020-03-12
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      相关资源
      最近更新 更多