确保var是向量的最简单方法 [英] Simplest way to ensure var is vector

查看:70
本文介绍了确保var是向量的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确保var是向量的最简单 /最短方法是什么?自写它可能看起来像

What is the "simplest"/shortest way to ensure a var is a vector? Self-written it could look like

(defn ensure-vector [x]
  (if (vector? x)
    x
    (vector x))

(ensure-vector {:foo "bar"})
;=> [{:foo "bar"}]

但是我想知道是否已经有一个核心功能可以做到? $ c> seq , vec vector list )要么在地图上失败,要么总是应用。

But I wonder if there is already a core function that does this? Many of them (seq, vec, vector, list) either fail on maps or always apply.

我还想知道该功能的最佳名称是什么。 box singleton 单位 v 广播向量到向量->向量!vector vector! vec!

I also wonder what would be the best name for this function. box, singleton, unit, v, cast-vector, to-vector, ->vector, !vector, vector!, vec!?

我进一步想知道其他语言(例如Haskell)是否内置此功能。

I further wonder if other languages, like Haskell, have this function built-in.

推荐答案

我认为当值是集合时要使用的函数是 vec 会将任何集合转换为向量。 vector 函数接收项所得向量作为参数,因此当值既不是向量也不是集合时可以使用它。

I think the function you want to use when the value is a collection is vec which turns any collection into a vector. The vector function receives the items of the resulting vector as its arguments, so you could use it when the value is neither a vector or a collection.

这是一种可行的方法:

(defn as-vector [x]
  (cond
    (vector? x) x
    (sequential? x) (vec x)
    :else (vector x)))

(map as-vector [[1] #{2 3} 1 {:a 1}])

我根据 Coercions clojure.java.io 中的c $ c>协议( as-file as- url )。

I chose the name for the function based on the ones from the Coercions protocol in clojure.java.io (as-file and as-url).

这篇关于确保var是向量的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆