LoginSignup
1
1

More than 5 years have passed since last update.

PureScript初心者のメモ(二次元配列から値を取り出す)

Last updated at Posted at 2018-11-26
value = [[1, 2, 3], [4, 5, 6]] :: Array (Array Int)

からvalue[0][0] ≒ (Just 1)を取り出したいときにどう書くべきか困ったのでメモ

0. 結論

index2 :: forall a. Array (Array a) -> Int -> Int -> Maybe a
index2 v i j = do
  dim1 <- index v i
  index dim1 j

index2 value 0 0  -- (Just 1)

以下はそれに至った流れです

1. ドキュメントを見つつとりあえず型を合わせた

関数型プログラミングを知らない人がドキュメント見ながら考えた結果こうなった

index (maybe [] identity $ index value 0) 0

不要な空配列が出てきてしまったので書き直してみる

2. bindを使う

indexの型が Array a -> Int -> Maybe a なので、flipを使って先にインデックスを与えると Array a -> Maybe a となり、bindでつなげられて空配列が消せた
flipが入ったために少し読みづらくなっているが、途中結果を変数に保存すれば解決する

index value 0 >>= flip index 0

3. do記法を使う

do記法を使ったら途中結果を変数に保存しなくても読みやすくできた

do
  firstArray <- index value 0
  index firstArray 0

Maybeのおかげで、この見た目でも配列の長さを超えた場合のエラー処理ができています

do
  firstArray <- index value 3
  index firstArray 0  -- Nothing

do
  firstArray <- index value 0
  index firstArray 3  -- Nothing
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1