dimanche 19 mai 2019

How do I compare tuples of a list with a value?

I'm trying to compare the Color tuple of all elements in a list. If they have the same color return true. If not return false. When I run the code the compiler throws an error.

I've used pattern matching plus nested if statement to check if the color of the head of the list matches with all the other elements.

type Suit = Clubs | Diamonds | Hearts | Spades
type Rank = Jack | Queen | King | Ace | Num of int
type Card = Rank * Suit
type Color = Red | Black
type Move = Discard of Card | Draw


let cards = [(Jack,Clubs); (Num(8),Spades)]

let card_color (c:Card) = 
  match c with
    | _, Clubs -> Black
    | _, Spades -> Black
    | _, Diamonds -> Red
    | _, Hearts -> Red

let all_same_color cs = 
  match cs with
    | [] -> true
    | x::xs -> 
      if not card_color cs.Head = card_color x then false else true
all_same_color cards

I expect it to return true if head matches colors with the other elements or false otherwise. F# throws the error: This value is not a function and cannot be applied.

Aucun commentaire:

Enregistrer un commentaire