Haskellの良さを俺にも分かるように教えて #3

3名無しさん@Next2ch:2015/12/14(月) 01:44:05.29 ID:81Uv0ueS

最近はじめた
練習でエイトクイーン書いたのでだれかコードレビューしてくれよん
MaybeからListに変換するあたりがどうすんのかよくわかってない

import System.IO
import Control.Applicative

main = do
let e = [[]] >>=putOne >>= putOne >>= putOne >>= putOne >>= putOne >>= putOne >>= putOne >>= putOne
print $ e !! 0
print $ e !! 1
print $ e !! 2
print $ e !! 3
print $ e !! 4
print $ length e

type Positions = [(Int, Int)]

-- put one queen on (x,y)
put :: Positions->Int->Int->Maybe Positions
put poss x y
| canPut poss x y = Just $ (x,y):poss
| otherwise = Nothing
where
canPut poss x y = (inBoard x y) && not (crossAny poss x y)
inBoard x y = all (\x->x `elem` [1..8]) [x,y]
cross pos x y = fst pos == x || snd pos == y || abs (fst pos - x) == abs (snd pos - y)
crossAny poss x y = any (\pos->cross pos x y) poss

-- put one queen on puttable place
putOne :: Positions -> [Positions]
putOne [] = map (:[]) $ (,) <$> [1..8] <*> [1..8]
putOne poss@(pos:_) = let xys = [(x,y) | x<-[1..8], y<-[1..8], x>fst pos || (x == fst pos && y>snd pos)] in
xys >>= (\(x,y)->maybeToList $ put poss x y)
where
maybeToList maybe = case maybe of
Nothing -> []
Just(a) -> [a]


スパムを通報

このレスがスパム・荒らしである場合は以下のボタンをクリックして通報してください。
(同意できない意見などに反対票を投じる機能ではありません)
通報

このスレッドを全て表示


レスを書き込む