Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.
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
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away