Sebastian Lindgren
Sebastian Lindgren

Reputation: 171

F# record list expressions

Hello my question is about list expressions in F#. I try to create a record that will be stored in a list. I want the Point record inside the Square record to update from 1-9. To clear out what I mean it's like when you write let example = [1 .. 1 .. 9] and get: val example : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9]. Here I want the Point in the Square record to change from pos = {x=1; y=1} and get all 9 Squares with the Points x=1; y=1 to x=9; y=9.

type Point = {x : int; y : int}
type Square = {pos : Point; side : int; X : int}  //A square got a position, a side length and a value

let defaultSquare = { pos = {x=1; y=1}; side = 10; X = 0 }

let spelplan = [{defaultSquare with pos = {x=1; y=1}} .. {defaultSquare with pos = {x=9; y=9}}]

I've tried the code above, I've also tried.

let spelplan = [{defaultSquare with pos = {x=1; y=1}} .. {defaultSquare with pos = {x=1; y=1}} .. {defaultSquare with pos = {x=9; y=9}}]

I then get a error message that it doesn't support the + operator.

I've already read this and this

Upvotes: 1

Views: 164

Answers (1)

Random Dev
Random Dev

Reputation: 52280

The reason your code is not working as you expect is, that F# does not know how to enumerate your Squares - you could try to implement + and stuff but instead I would just create the positions (using said list expressions) and then map them into a Square list:

let fromPos size v x y = 
    { pos = {x=x; y=y}
    ; side = size
    ; X = v 
    }

[for y in 1..9 do for x in 1..9 -> fromPos 10 0 x y]

as an alternative you can do

[for y in 1..9 do for x in 1..9 -> (x,y)]
|> List.map (fun (x,y) -> fromPos 10 0 x y)

as well of course

The only interesting thing here is surley the way I produce the positions - you can generalize it like this:

let positions width height =
    [ for y in 1..height do for x in 1..width -> (x,y) ]

which will produce a list of (x,y)-tuples from (1,1) to (width,height)

Upvotes: 1

Related Questions