Clojure ::获取列表的单个元素,如果列表包含多个元素,则抛出异常 [英] Clojure :: get the single element of a list and throw exception if the list has more than 1 elements

查看:61
本文介绍了Clojure ::获取列表的单个元素,如果列表包含多个元素,则抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中的某个点知道列表仅包含一个元素,因此我可以通过

I know at a certain point in my code that a list only has one element so I obtain it with

(first alist)

但是如果列表中有多个要提醒的元素,我也希望代码中断我的状态错误。在Clojure中实现这一目标的惯用方式是什么?

But I would also like the code to break if the list has more than one elements to alert me of the erroneous condition. What's an idiomatic way to achieve that in Clojure ?

推荐答案

首先替换 具有仅 (或其他诗名)的函数,该函数具有要在其中声明的前提:

Replace first with an only (or other poetically named) function with a pre-condition where you want to make your assertion:

(defn only [x] {:pre [(nil? (next x))]} (first x))

(only [1])
=> 1

(only [1 2])
=> AssertionError Assert failed: (nil? (next x))  user/only (NO_SOURCE_FILE:1)

这篇关于Clojure ::获取列表的单个元素,如果列表包含多个元素,则抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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