0

I have the following type in F#:

type CodeNameError(CodeNameCombination: (Code*Name)[]) =
member this.CodeNameCombinations = CodeNameCombination

Is there a way to turn the (Code*Name)[] into a named tuple array in F#? In c# I would do something like:

public CodeNameError((Code code, Name name)[] codeName)
{
    CodeNameCombination = codeName
}

1 Answer 1

5

F# does not have named tuples in the same way in which C# has them, but there are a couple of alternatives. My preferred option would actually be to just define a new record type for the Code * Name pair. If you get into a situation where you want to name things, a record is a good choice and it takes 1 line of code:

type NamedCode = { Name:Name; Code:Code }

type CodeNameError(codeNameCombination:NamedCode[]) =
  member this.CodeNameCombinations = codeNameCombination

CodeNameError [| { Code = "1+1"; Name = "test" } |]

If you do not want to define a type (but I'm not sure why you wouldn't want to do this), you could use anonymous records:

type CodeNameError(CodeNameCombination: {| code:Code; name:Name |}[]) =
  member this.CodeNameCombinations = CodeNameCombination

CodeNameError [| {| code = "1+1"; name = "test" |} |]
1
  • 2
    I had been passing a named tuple from c# into an F# type which took a tuple. The output at the end looked a little wonky. Thanks for the info.
    – Rolan
    Apr 17, 2020 at 21:32

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.