0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NimAdvent Calendar 2023

Day 19

Nimでセマンティックバージョン比較

Posted at

phpのversion_compare関数のような関数を作りたかった。

import strutils

proc compareVersions(version1, version2: string): int =
  var parts1 = version1.split('.')
  var parts2 = version2.split('.')

  # メジャー、マイナー、パッチと順に確認する。
  for i in 0 .. min(parts1.len, parts2.len) - 1:
    let num1 = parseInt(parts1[i])
    let num2 = parseInt(parts2[i])
    
    if num1 < num2:
      return -1
    elif num1 > num2:
      return 1

  # 桁数が多い方が大きいとする
  if parts1.len < parts2.len:
    return -1
  elif parts1.len > parts2.len:
    return 1

  return 0

試しに実行してみよう

test.nim
# ここはさっきと同じ。
import strutils

proc compareVersions(version1, version2: string): int =
  var parts1 = version1.split('.')
  var parts2 = version2.split('.')
  
  for i in 0 .. min(parts1.len, parts2.len) - 1:
    let num1 = parseInt(parts1[i])
    let num2 = parseInt(parts2[i])
    
    if num1 < num2:
      return -1
    elif num1 > num2:
      return 1

  if parts1.len < parts2.len:
    return -1
  elif parts1.len > parts2.len:
    return 1

  return 0


# 使用例
let storedVersion = "2.3.1"
let currentVersion = "2.3.0"

let result = compareVersions(storedVersion, currentVersion)

if result > 0:
  echo "アップデートが必要です."
elif result < 0:
  echo "アップデートは不要です."
else:
  echo "バージョンは同じです."

test.nimを作ったら下記で実行

$ nim c -r test.nim
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?