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

ElmでUUID生成をTask化する

「UUID生成をTask化できないか」という相談に対して「できないだろうな」と思っていたが、@niso1985さんができる方法を見つけてくれたので日本語でも検索に引っかかるようメモとして残しておく。

以下の例はTSFoster/elm-uuidをつかったケース。
これまでUUIDを生成するには以下のように一度Cmdにしないと受け取れないのかと思っていた。

Cmd使う版
init : () -> ( Model, Cmd msg )
init _ =
    ( { uuid = "" }, Random.generate UUIDGenerated UUID.generator )


type Msg
    = UUIDGenerated UUID


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        UUIDGenerated value ->
            ( { value = UUID.toString value }, Cmd.none )

しかしこんな感じで書くこともできるらしい。

Task使う版
import UUID exposing (UUID)
import Task exposing (Task)
import Random
import Time


newUUID : Task Never UUID
newUUID =
    Task.map (Tuple.first << Random.step UUID.generator << Random.initialSeed << Time.posixToMillis) Time.now

こうすればUUIDが必要な任意の処理をTaskとしてチェーンして書ける。これはうれしい。
懸念点として、Taskのほうは現在時刻をシードとして使うため推測されやすいUUIDになる可能性があるとのこと。

参考: https://gist.github.com/JoelQ/c93a8f6a81262ff12c93ab2ff859f8e5

Why not register and get more from Qiita?
  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
No 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
ユーザーは見つかりませんでした