計算機科学のブログ

コンテキストでの型の操作 コンテキストとしてのリスト:Applicative型クラスをさらに掘り下げる コンテキストとしてのリスト 例:大量のテストデータをすばやく生成する

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON 29(コンテキストとしてのリスト:Applicative型クラスをさらに掘り下げる)、29.3(コンテキストとしてのリスト)、例:大量のテストデータをすばやく生成する、クイックチェック 29-5の解答を求めてみる。

コード

lesson/app/Main.hs

module Main (main) where

import Lib (User (..))

testNames :: [String]
testNames =
  [ "John Smith",
    "Robert'); DROP TABLE Students;--",
    "Christina NULL",
    "Randall Munroe",
    "Will Kurt"
  ]

testIds :: [Int]
testIds =
  [ 1337,
    0123,
    999999
  ]

testScores :: [Int]
testScores =
  [ 0,
    100000,
    -99999
  ]

testData :: [User]
testData =
  pure User
    <*> testNames
    <*> testIds
    <*> testScores

main :: IO ()
main = do
  print $ take 10 testData
  print $ take 10 $ reverse testData
  print $ length testData == 45

lesson/src/Lib.hs

module Lib
  ( User (..),
  )
where

data User = User
  { name :: String,
    gamerId :: Int,
    score :: Int
  }
  deriving (Show)

入出力結果(Terminal, Zsh)

% stack exec lesson-exe
[User {name = "John Smith", gamerId = 1337, score = 0},User {name = "John Smith", gamerId = 1337, score = 100000},User {name = "John Smith", gamerId = 1337, score = -99999},User {name = "John Smith", gamerId = 123, score = 0},User {name = "John Smith", gamerId = 123, score = 100000},User {name = "John Smith", gamerId = 123, score = -99999},User {name = "John Smith", gamerId = 999999, score = 0},User {name = "John Smith", gamerId = 999999, score = 100000},User {name = "John Smith", gamerId = 999999, score = -99999},User {name = "Robert'); DROP TABLE Students;--", gamerId = 1337, score = 0}]
[User {name = "Will Kurt", gamerId = 999999, score = -99999},User {name = "Will Kurt", gamerId = 999999, score = 100000},User {name = "Will Kurt", gamerId = 999999, score = 0},User {name = "Will Kurt", gamerId = 123, score = -99999},User {name = "Will Kurt", gamerId = 123, score = 100000},User {name = "Will Kurt", gamerId = 123, score = 0},User {name = "Will Kurt", gamerId = 1337, score = -99999},User {name = "Will Kurt", gamerId = 1337, score = 100000},User {name = "Will Kurt", gamerId = 1337, score = 0},User {name = "Randall Munroe", gamerId = 999999, score = -99999}]
True
%