1

I'm trying check an array if it is arranged. The problem is that in the method Verificar Fsharp ignore the if and 'ordenado' take always the value 0.

open System

type VerificarOrden() = 
  let valor = Array.empty
  let (valor : int array) = Array.create 10 1
  let ordenado = 0

  member this.Inicializar() = 
    for f in 0 .. valor.Length - 1 do
      printfn "Introduzaca el valor %d: " f
      let res=System.Console.ReadLine()
      Array.set valor f (System.Int32.Parse(res))

    member this.Verificar() = 
      for f in 1 .. valor.Length - 1 do
        if valor.[f] > valor.[f-1]
        then ordenado = 0
        else ordenado = 1
        printfn "f: %d\nanterior: %d\nordenado: %d\n" valor.[f] valor.[f-1] ordenado

    member this.Imprimir() =
      if ordenado = 0 
      then printfn "La matriz esta ordenada"
      else printfn "La matriz no esta ordenada"

let chekear = VerificarOrden()
chekear.Inicializar()
chekear.Verificar()
chekear.Imprimir()

Because of this, it always shows that the array is arranged although it isn't

2 Answers 2

3

Variables in F# are by default immutable: they never change and can't be updated. So the code

Type VerificarOrden()
    let ordenado = 0
    ...

means essentially that ordenado is a constant with value 0. In your conditional

    if valor.[f] > valor.[f-1]
    then ordenado = 0
    else ordenado = 1

the equal-sign does not update the constant ordenado–that would be meaningless–but rather, it tests whether the value of ordenado is 0, returning a boolean. The above code has the same semantics as

    if valor.[f] > valor.[f-1]
    then true
    else false

The compiler/interpreter likely tried to tell you as much with the warning

warning FS0020: This expression should have type 'unit', but has type 'bool'. Use 'ignore' to discard the result of the expression, or 'let' to bind the result to a name.

You want ordenado to be mutable. This is what you want, then:

type VerificarOrden() = 
    ...
    let mutable ordenado = 0

    ...
    if valor.[f] > valor.[f-1]
    then ordenado <- 0
    else ordenado <- 1
    ...

The mutable keyword means that the value of ordenado can be changed. The assignment ordenado <- 0 then changes the value.

By the way, once you've made ordenado mutable, your program still has a bug in that it thinks the sequence 0-1-2-3-4-5-6-8-7-9 is ordered. I'll leave that as an exercise ;-)

0

The problem with your code is

 ordenado = 1

this is not an assignment but a comparison. In F# = operator has two meanings, binding (not assignment) to let statements or comparison

You can't assign to a let bound field, they are immutable. To assign it you should make it mutable and use <- operator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.