什麼時候應該在函數中使用函數而不是單獨的私有函數?什麼時候應該在函數中使用函數而不是單獨的私有函數?
我觀察到我寫的函數是相當長:
let optionsFor piece (positions:Space list) =
let yDirection = match piece with
| Black _ -> -1
| Red _ -> 1
let sourceX , sourceY =
match piece with
| Black (checker , pos) -> pos
| Red (checker , pos) -> pos
let optionsForPiece =
(fun pos -> pos = ((sourceX - 1) , (sourceY + yDirection)) ||
pos = ((sourceX + 1) , (sourceY + yDirection)))
let availableSelection =
(fun space -> match space with
| Available pos -> Some pos
| Allocated _ -> None)
let availablePositions =
positions |> List.filter toAvailable
|> List.choose availableSelection
availablePositions |> List.filter optionsForPiece
因此,我認爲重構上面的功能成幾個小的功能。
但是,我不確定這是否是函數式編程所必需的。
目前關於內部函數的建議與將其提取到私有函數有什麼不同?
附錄:
open NUnit.Framework
open FsUnit
(* Types *)
type Black = BlackKing | BlackSoldier
type Red = RedKing | RedSoldier
type Coordinate = int * int
type Piece =
| Black of Black * Coordinate
| Red of Red * Coordinate
type Space =
| Allocated of Piece
| Available of Coordinate
type Status =
| BlacksTurn | RedsTurn
| BlackWins | RedWins
(* Functions *)
let black coordinate = Allocated (Black (BlackSoldier , coordinate))
let red coordinate = Allocated (Red (RedSoldier , coordinate))
let startGame() =
[ red (0,0); red (2,0); red (4,0); red (6,0)
red (1,1); red (3,1); red (5,1); red (7,1)
red (0,2); red (2,2); red (4,2); red (6,2)
Available (1,3); Available (3,3); Available (5,3); Available (7,3)
Available (0,4); Available (2,4); Available (4,4); Available (6,4)
black (1,5); black (3,5); black (5,5); black (7,5)
black (0,6); black (2,6); black (4,6); black (6,6)
black (1,7); black (3,7); black (5,7); black (7,7) ] , BlacksTurn
let private toAvailable =
(fun space -> match space with
| Available pos -> true
| _ -> false)
let available (positions:Space list) = positions |> List.filter toAvailable
let optionsFor piece (positions:Space list) =
let yDirection = match piece with
| Black _ -> -1
| Red _ -> 1
let sourceX , sourceY =
match piece with
| Black (checker , pos) -> pos
| Red (checker , pos) -> pos
let optionsForPiece =
(fun pos -> pos = ((sourceX - 1) , (sourceY + yDirection)) ||
pos = ((sourceX + 1) , (sourceY + yDirection)))
let availableSelection =
(fun space -> match space with
| Available pos -> Some pos
| Allocated _ -> None)
let availablePositions =
positions |> List.filter toAvailable
|> List.choose availableSelection
availablePositions |> List.filter optionsForPiece
我不知道這是否更適合[Code Review](http://codereview.stackexchange.com/)。 – s952163
我的代碼只是用作上下文。我認爲這個問題甚至不需要代碼。我想我正在尋找每個選項的優點和缺點。 –
我不完全確定這是否是你所要求的,但是這應該由你的使用決定,如果你想/從外部訪問函數(函數和你的模塊以及其他.NET代碼)。定義許多小函數和內部函數沒有什麼不妥,只要你組織它們。 – s952163